-1

我有一个多维关联数组“$nav_menus”,如下所示:

Array
(
[0] => Array
    (
        [id] => 1
        [menu_name] => Media
        [parent_id] => 0
        [submenus] => 1
    )

[1] => Array
    (
        [id] => 2
        [menu_name] => Movies
        [parent_id] => 1
        [submenus] => 1
    )

[2] => Array
    (
        [id] => 3
        [menu_name] => English Movies
        [parent_id] => 2
        [submenus] => 1
    )

[3] => Array
    (
        [id] => 4
        [menu_name] => Action
        [parent_id] => 3
        [submenus] => 1
    )

)

我想要完成的是循环数组,只要键 ['parent_id'] 的值不等于 0,就是再次循环数组并将其移动到任何菜单中 ['id' 的值] 键等于 parent_id ...这是我希望 $nav_menus 最后的样子

Array
(
    [id] => 1
    [menu_name] => Media
    [parent_id] => 0
    [submenus] => 1
    [0] => Array
        (
            [id] => 2
            [menu_name] => Movies
            [parent_id] => 1
            [submenus] => 1
            [0] => Array
                (
                    [id] => 3
                    [menu_name] =>English Movies
                    [parent_id] => 2
                    [submenus] => 1
                    [0] => Array
                        (
                            [id] => 4
                            [menu_name] => Action
                            [parent_id] => 3
                            [submenus] => 1
                        )
                )
        )
)

这是我试图完成的,但没有运气:

foreach($nav_menus as $k => $v){
if($v['parent_id'] !== 0){
    $x = $v;
    foreach($nav_menus as $key => $value){
        if($value['id'] == $v['parent_id']){
            unset($v);
            array_push($value, $x);             
            break;
        }
    }
}
}
print_r($nav_menus);

它给了我相同的原始数组,没有任何改变:( ...有什么建议吗?

4

1 回答 1

0

试试这个递归函数。

function array_new($arr1,$tot_count,$parent=0,$new_arr=array(),$global_count=0)
{
        $count=0;

        foreach($arr1 as $arr_res)
        {
             if($arr_res['parent_id']==$parent)
             {
                 $new_arr['id'] =  $arr_res['id'];
                 $new_arr['menu_name'] =  $arr_res['menu_name'];
                 $new_arr['parent_id'] =  $arr_res['parent_id'];  
                 $new_arr['submenus'] =  $arr_res['submenus']; 
                 //DebugBreak();
                 if($global_count<$tot_count-1)
                 {  $global_count++;
                   $new_arr[$count] = array_new($arr1,$tot_count,$arr_res['id'],$new_arr,$global_count);
                   $count++;

                 } 
             }



        }

        return   $new_arr;

}

'$arr_unformated' 是您现在拥有的数组。

$tot_count = count($arr_unformated);
$arrnew = array_new($arr_unformated,$tot_count);

'$arrnew' 是你的愿望数组。

于 2013-06-10T08:04:20.813 回答