我正在尝试以有效的方式将 PHP 中的查询结果分组为关联数组。我可以使用多个嵌套的 foreach 循环,检查当前 id 字段是否与每个数组组的前一个匹配,但我猜这个问题有更好/更有效的解决方案。有没有人有一个聪明的解决方案?理想情况下,可以对给定键字段或嵌套键字段数组的任何查询结果集进行分组的通用函数或方法?
这是查询结果数组:
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] =>
)
)
这是我想将其转换为的数组:
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()
)
)
)
)
)
分组关系说明:
一个look可以有1个或多个服装物品。一件服装物品可以有一个或多个服装品牌。外观服装文章可以有一个或多个属性。一个服装品牌可以有一个或多个属性。