Reputation: 65
I want to build a nested array from a simple table with Laravel Eloquent, but i couldn't.
So basically below is a snap shot of my table
and this is the array I want to build
Upvotes: 0
Views: 53
Reputation: 9303
You can use some methods from collection :
$result = $data->groupBy(['market_id', 'base_currency', 'currency_id'])
->map(function ($item) {
return $item->map(function ($item) {
return $item->map(function ($item) {
return $item->map(function ($item) {
return $item['currency_id'];
});
})->flatten();
})->sortKeys();
});
dd($result->toArray());
array:1 [
1 => array:2 [
1 => array:2 [
0 => 2
1 => 3
]
2 => array:2 [
0 => 1
1 => 2
]
]
]
groupBy
The groupBy
method groups the collection's items by a given key. Multiple grouping criteria may be passed as an array. Each array element will be applied to the corresponding level within a multi-dimensional array:
$data->groupBy(['market_id', 'base_currency', 'currency_id']);
map
The map
method iterates through the collection and passes each value to the given callback.
->map(function ($item) {
return $item;
});
flatten
The flatten
method flattens a multi-dimensional collection into a single dimension:
->flatten()
sortKeys
The sortKeys
method sorts the collection by the keys of the underlying associative array:
->sortKeys()
Upvotes: 2