I'm trying to group query results in PHP as an associative array in an efficient manner. I could use multiple nested foreach loops, checking if the current id field matches the previous for each array group, but I'm guessing there are better/more efficient solutions to this problem. Does anyone have a clever solution for this? Ideally a generic function or method that can group any query result set given a key field or array of nested key fields?
Here is the query results array:
Array
(
[0] => Array
(
[look_id] => 3
[look_name] => Test Look
[look_description] => description here
[clothing_article_id] => 1
[clothing_article_name] => Coat
[look_clothing_article_attribute_id] => 1
[look_clothing_article_attribute_name] => Purple
[clothing_brand_name] => Gap
[clothing_article_brand_price] => 40.00
[clothing_article_brand_attribute_price] => 50.00
[clothing_article_brand_attribute_name] => Purple
)
[1] => Array
(
[look_id] => 3
[look_name] => Test Look
[look_description] => description here
[clothing_article_id] => 1
[clothing_article_name] => Coat
[look_clothing_article_attribute_id] => 2
[look_clothing_article_attribute_name] => Black
[clothing_brand_name] => Gap
[clothing_article_brand_price] => 40.00
[clothing_article_brand_attribute_price] =>
[clothing_article_brand_attribute_name] =>
)
[2] => Array
(
[look_id] => 3
[look_name] => Test Look
[look_description] => description here
[clothing_article_id] => 2
[clothing_article_name] => Pants
[look_clothing_article_attribute_id] => 3
[look_clothing_article_attribute_name] => Cuffed
[clothing_brand_name] =>
[clothing_article_brand_price] =>
[clothing_article_brand_attribute_price] =>
[clothing_article_brand_attribute_name] =>
)
)
And this is the array I'd like to convert it to:
Array
(
'looks' => Array(
[0] => Array(
'id' => 3,
'name' => 'Test Look',
'description' => 'description here',
'clothingArticles' => Array(
[0] => Array(
'id' => 1,
'name' => 'Coat',
'attributes' => Array(
[0] => Array(
'id' => 1,
'name' => 'Purple'
'brands' => Array(
[0] => Array(
'name' => 'Gap',
'price' => 50.00
)
)
),
[1] => Array(
'id' => 2,
'name' => 'Black'
)
),
'brands' => Array(
[0] => Array(
'name' => 'Gap',
'price' => 40.00
)
)
),
[1] => Array(
'id' => 2,
'name' => 'Pants',
'attributes' => Array(
[0] => Array(
'id' => 3,
'name' => 'Cuffed'
'brands' => Array()
)
),
'brands' => Array()
)
)
)
)
)
Explanation of grouping relationships:
A look can have 1 or many clothing articles. A clothing article can have 1 or many clothing brands. A look clothing article can have 1 or many attributes. A clothing article brand can have 1 or many attributes.