'laravel convert many collection to single array
I have a problem with my foreach. I have collection data like this:
["post access", "post create", "post read", "post update", "post delete", "publish access", ...]
but I need to convert that into this:
[
"name" => "post",
"access" => false,
"create" => false,
"read" => false,
"update" => false,
"delete" => false
], [
"name" => "publish",
"access" => false
], [...]
btw I'm still on progress of learning laravel-permission, and I make that for the checkbox in the blade.
how did I make that? please help me. Thanks
Solution 1:[1]
You have to use both String Helpers and Collection Methods for this.
$collection = collect(["post access", "post create", "post read", "post update", "post delete", "publish access", ...]);
$array = array();
$collection->each(function($item. $key){
if(Str::contains(['post','get'], $item) && (! isset($array[0]['name']))){
$array[0]['name'] = Str::before(' ', $item);
}
if (Str::contains(['access','create','read','update','delete'], $item){
$name_removed = Str::remove($array[0]['name'] . ' ', $item);
$array[0][$name_removed] = false;
}
if (Str::contains('publish access', $item){
$array[1]['name'] = Str::remove(' access', $item);
$array[1]['access'] = false;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
