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?
You can use laravel
Collections
First you need to group by the
groupBy
method, thenmap
each group and merge each sub-array.