我有一个对象数组,例如:
Array
(
[0] => Array
(
[Id] => 1
[Name] => Toy Car
[Category] => Toys
[Price] => 2.99
[OnSale] => false
)
...
)
但我希望他们按类别分组,然后按OnSale分组。
到目前为止,我已经能够按类别分组:
$result = array();
foreach ($data as $element) {
$result[$element['Category']][] = $element;
}
但我不确定如何嵌套另一个foreach或者按类别对它们进行递归分组。任何帮助表示赞赏!
答案 0 :(得分:1)
你的意思是:
$result = array();
foreach ($data as $element) {
$result[$element['Category']][$element['OnSale']][] = $element;
}
编辑:抱歉,[
和]
所有问题......
答案 1 :(得分:1)
你很亲密!您只需要添加要分组的第二个键。
$byCategoryAndSale = [];
foreach ($inventory as $item) {
$byCategoryAndSale[$item['Category']][$item['OnSale']][] = $item;
}
注意使用布尔值作为数组键将等于1和0,这可能会让人感到困惑。
以下是一个完整的例子:
<?php
$inventory = [
[
'Id' => 1,
'Name' => 'Toy Car',
'Category' => 'Toys',
'Price' => 2.99,
'OnSale' => false
],
[
'Id' => 2,
'Name' => 'Another Toy',
'Category' => 'Toys',
'Price' => 1.99,
'OnSale' => false
],
[
'Id' => 3,
'Name' => 'Hamburger',
'Category' => 'Not Toys',
'Price' => 5.99,
'OnSale' => false
],
[
'Id' => 4,
'Name' => 'Last Toy',
'Category' => 'Toys',
'Price' => 50.99,
'OnSale' => true
]
];
$byCategoryAndSale = [];
foreach ($inventory as $item) {
$byCategoryAndSale[$item['Category']][$item['OnSale']][] = $item;
}
print_r($byCategoryAndSale);
?>
哪个收益率:
PS C:\> php test.php
(
[Toys] => Array
(
[0] => Array
(
[0] => Array
(
[Id] => 1
[Name] => Toy Car
[Category] => Toys
[Price] => 2.99
[OnSale] =>
)
[1] => Array
(
[Id] => 2
[Name] => Another Toy
[Category] => Toys
[Price] => 1.99
[OnSale] =>
)
)
[1] => Array
(
[0] => Array
(
[Id] => 4
[Name] => Last Toy
[Category] => Toys
[Price] => 50.99
[OnSale] => 1
)
)
)
[Not Toys] => Array
(
[0] => Array
(
[0] => Array
(
[Id] => 3
[Name] => Hamburger
[Category] => Not Toys
[Price] => 5.99
[OnSale] =>
)
)
)
)