如何合并两个数组,其中一个数组是动态嵌套值

时间:2016-08-01 07:34:19

标签: php arrays

我有两个像这样的阵列

$ whole_orders

Array
(
    [2] => Array
        (
            [0] => Array
                (
                    [id] => 3
                    [food_id] => 1
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [food_id] => 2
                )

            [1] => Array
                (
                    [id] => 1
                    [food_id] => 1
                )

        )

)

$ array

Array
(
    [2] => Array
        (
            [0] => Array
                (
                    [count] => 1
                    [subtotal] => 103.42
                    [tax] => 18.42
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [count] => 2
                    [subtotal] => 303.42
                    [tax] => 38.42
                )

        )

)

这里我有两个数组,例如$whole_orders & $array,我需要将 $array 值合并到 $whole_orders ..

$whole_orders具有动态的嵌套值..

最后我的数组应该是这样的..

Array
(
    [2] => Array
        (
            [0] => Array
                (
                    [id] => 3
                    [food_id] => 1
                )

            [1] => Array
                (
                    [count] => 1
                    [subtotal] => 103.42
                    [tax] => 18.42
                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [food_id] => 2
                )

            [1] => Array
                (
                    [id] => 1
                    [food_id] => 1
                )
            [2] => Array
                (
                    [count] => 2
                    [subtotal] => 303.42
                    [tax] => 38.42
                )
        )

)

它应该附加$whole_orders数组的..

的嵌套值

如果您认为我的标题不正确,请更改它..

提前致谢..

3 个答案:

答案 0 :(得分:2)

使用foreach并迭代$ array并分配给$ whole_orders

<?php


 // if $array is always single dimension array   
foreach($array as $array_key=>$array_val)
{
    $whole_orders [$array_key][]=$val[0];    
}

// or if $array is multi dimension array
foreach($array as $array_key=>$array_val)
{
    foreach($array_val as $key=>$val)
    {
        $whole_orders [$array_key][]=$val;
    }

}

?>

答案 1 :(得分:1)

这样做就可以实现你想要的输出,但是当两个数组的计数相同时

foreach($array as $arrayKey => $arrayValue){
    foreach($arrayValue as $key => $value){
        $whole_orders[$arrayKey][] = $value;
    }
}

print_r($whole_orders);

答案 2 :(得分:1)

您可以尝试以下方法..

$arr3 = array();
   foreach($arr1 as $key => $value) :
       $arr3[$key] = $value;
       if(isset($arr2[$key])) :
           foreach($arr2[$key] as $k=>$val) :

               $arr3[$key][] = $val;
            endforeach;
        endif;
   endforeach;
   print_r($arr3);