Level 20
Go with this : https://laravel.com/docs/5.7/collections#method-maptogroups
$grouped = $collection->mapToGroups(function ($item, $key) {
return [$item['filter'] => $item['value']];
});
$grouped->toArray();
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Thanks in advance! I have the following collection.
$collection = collect([
[
'id' => 1,
'filter' => 'brand',
'value' => 'apple'
],
[
'id' => 2,
'filter' => 'color',
'value' => 'red'
],
[
'id' => 3,
'filter' => 'color',
'value' => 'blue'
],
[
'id' => 3,
'filter' => 'storage',
'value' => '8GB'
]
]);
I need it exactly like this:
[
"brand" => ["apple"],
"color" => ["red", "blue"],
"storage" => ["8GB"]
]
Or I need to transform it like this:
$transformed = collect([
[
'filter' => 'brand',
'value' => ['apple']
],
[
'filter' => 'color',
'value' => ['red', 'blue']
],
[
'filter' => 'storage',
'value' => ['8GB']
]
]);
How can I do this?
Go with this : https://laravel.com/docs/5.7/collections#method-maptogroups
$grouped = $collection->mapToGroups(function ($item, $key) {
return [$item['filter'] => $item['value']];
});
$grouped->toArray();
Please or to participate in this conversation.