PHP - 在同一个键上合并两个数组

时间:2016-05-10 07:50:49

标签: php arrays multidimensional-array

我想在同一个键上合并两个数组。

这是第一个阵列:

Array
(
[2052] => Array
    (
        [495] => Array
            (
                [0] => Array
                    (
                        [ID_RI_BELANJA] => 79755
                    )

                [1] => Array
                    (
                        [ID_RI_BELANJA] => 79755
                    )
            )

    )

[4566] => Array
    (
        [488] => Array
            (
                [0] => Array
                    (
                        [ID_RI_BELANJA] => 231610
                    )

                [1] => Array
                    (
                        [ID_RI_BELANJA] => 231610
                    )
            )

    )
)

这是第二个数组

Array
(
[2052] => Array
    (
        [495] => Array
            (
                [TOTAL_RI] => 1000000
                [TOTAL_ANGGARAN] => 500000
            )

    )

[4566] => Array
    (
        [488] => Array
            (
                [TOTAL_RI] => 2000000
                [TOTAL_ANGGARAN] => 1000000
            )

    )
)

我想将两个数组合并为:

Array
(
[2052] => Array
    (
        [495] => Array
            (
                [0] => Array
                    (
                        [ID_RI_BELANJA] => 79755
                    )

                [1] => Array
                    (
                        [ID_RI_BELANJA] => 79755
                    )

                [TOTAL_RI] => 1000000
                [TOTAL_ANGGARAN] => 500000
            )

    )

[4566] => Array
    (
        [488] => Array
            (
                [0] => Array
                    (
                        [ID_RI_BELANJA] => 231610
                    )

                [1] => Array
                    (
                        [ID_RI_BELANJA] => 231610
                    )

                [TOTAL_RI] => 2000000
                [TOTAL_ANGGARAN] => 1000000
            )

    )
)

这是我的第一个项目,我不知道该怎么做。

谁能告诉我怎么做?

PLS

4 个答案:

答案 0 :(得分:1)

=>将所有值存储在此变量中

 $Arr1 //put your value in this array 
 $Arr2 //put your value in this array 

=>合并它

$ResponseDetails    = array_merge( (array)$Arr1, (array)$Arr2);

答案 1 :(得分:0)

如果你的阵列有相同的密钥,那么:

method

答案 2 :(得分:0)

假设你的两个数组分别是$ array1和$ array 2,试试这个:

foreach($array1 as $k1 => $v1) {
    foreach($v1 as $k2 => $v2) {
       foreach($v2 as $k3 => $v3) {
          $new[$k1][$k2][$k3] = $array1[$k1][$k2][$k3];
          $new[$k1][$k2] = array_merge($new[$k1][$k2], $array2[$k1][$k2]);
       }
   }  
}

答案 3 :(得分:0)

array_replace_recursive应该做的工作:

// $arr1 is the 1st array, $arr2 - is your 2nd array
$result = array_replace_recursive($arr1, $arr2);  // now the $result variable contains the expected merged result

http://php.net/manual/en/function.array-replace-recursive.php