I have a query that returns the names of categories and their subcategories.
$subcategories = Subcategory::select('subcategories.name as subcatname', 'categories.name as catname') ->join('categories', 'subcategories.idCategory', '=', 'categories.id') ->get();
Now the results I get are as follows:
'Music' => 'Jazz', 'Music' => 'Rock', 'Music' => 'Pop', 'Movie' => 'Action'
How can I group it like this:
'Music' => array('Jazz', 'Rock','Pop'), 'Movies' => array('Action')
Is it possible without too many loop iterations and check which subcategory belongs to which category?
P粉5133181142024-04-05 00:21:42
You can use laravelCollections
First you need to group by the groupBy
method, then map
each group and merge each sub-array.
$result = collect($subcategories) ->groupBy('catname') ->map(function ($item) { return array_merge($item->toArray()); })->all();