如何将数组移动到另一个?

时间:2013-06-10 07:12:40

标签: php arrays loops

我有一个多维关联数组“$ 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);

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

1 个答案:

答案 0 :(得分: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'是你渴望的阵容。