我有以下foreach循环:
foreach($mydata as $data){
$section = $data->section;
$category = $data->category;
$item = $data->item;
}
我想像这样构建树:
- section
_ category
- items
...
现在我确实喜欢这个:
$tmp = [];
$newarray = [];
foreach($mydata as $data){
$section = $data->section;
$category = $data->category;
$item = $data->item;
if( !in_array($category, $temp)){
$newarray[$section][] = $category;
}
}
// output:
Array(
[SectionName_one] => Array(
[0] => categoryOneName_one
[1] => categoryOneName_two
[2] => categoryOneName_three
)
[SectionName_two] => Array(
[0] => categoryTwoName_one
[1] => categoryTwoName_two
[2] => categoryTwoName_three
)
...
)
我在这里被封锁,我不知道如何为每个类别插入项目元素,如果你有一个想法感谢帮助我:)
谢谢
答案 0 :(得分:1)
foreach ($mydata as $data){
$newarray[$data->section][$data->category][]= $data->item;
}
PHP对于不存在的数组键非常宽容。