多维数组Foreach树

时间:2013-08-06 13:50:14

标签: php arrays

我尝试使用数组并使用父级和子级创建一个新的多维。我觉得我能够接近,但是看起来还是不对劲。

$value->menu_item_parent //Contains the parent value that can be used for key

我错过了什么?

$the_mega = array();
foreach ($menuitems as $key => $value) {
    if ($value->menu_item_parent=='0') {
        $the_mega["parents"][]=$value->title;
    }else{
        $the_mega[$value->title]["childs"]=$value->title;
    }       
}
}
echo '<pre>';
print_r($the_mega);
echo '</pre>';

 Array
(
    [parents] => Array
        (
            [0] => Parent 1
            [1] => Parent 2
        )

    [Child 1] => Array
        (
            [childs] => Child 1
        )

    [Child 2] => Array
        (
            [childs] => Child 2
        )

    [Child 3] => Array
        (
            [childs] => Child 3
        )

)

1 个答案:

答案 0 :(得分:0)

试试这个:

$the_mega = array();
foreach ($menuitems as $key => $value) {
    if ($value->menu_item_parent=='0') {
        $the_mega[$key]['parents'][]=$value->title;
    }else{
        $the_mega[$value->title]['childs'][]=$value->title;
    }       
}