I want to convert all of my static data to collection in Laravel.
This is my data:
static $menu_list = [
[
'path' => 'admin/report/transaction',
'active' => 'admin/report',
'name' => 'Report',
'icon' => 'file-text',
'children' => [
'path' => 'admin/report/transaction',
'active' => 'admin/report/transaction',
'name' => 'Transaction',
],
],
];
This function converts my data to array:
public static function menuList()
{
$menu_list = collect(self::$menu_list)->map(function ($voucher) {
return (object) $voucher;
});
}
but function above can only convert main of array, it can't convert children => [...]
to collection.
You need a recursive call.
public static function convertToCollection()
{
$menu_list = self::menuList(self::$menu_list);
}
public static function menuList($list)
{
return collect($list)->map(function ($voucher) {
if(is_array($voucher)) {
return self::menuList($voucher)
}
return $voucher;
});
}
You need to use collect()
inside map()
again:
public static function menuList()
{
$menu_list = collect(self::$menu_list)->map(function ($voucher) {
return (object) array_merge($voucher, [
'children' => collect($voucher['children'])
]);
});
}
Just add a small code peace to your approach.
$menu_list = collect(self::$menu_list)->map(function ($voucher) {
$voucher['children'] = (object) $voucher['children'];
return (object) $voucher;
});
Output
Illuminate\Support\Collection {#574 ▼
#items: array:1 [▼
0 => {#573 ▼
+"path": "admin/report/transaction"
+"active": "admin/report"
+"name": "Report"
+"icon": "file-text"
+"children": {#567 ▼
+"path": "admin/report/transaction"
+"active": "admin/report/transaction"
+"name": "Transaction"
}
}
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.