PHP Merge Array并保持密钥

时间:2017-08-01 09:59:38

标签: php arrays merge

我想加入两个数组,其中1个键应该加入它们。

    array:1 [
      0 => array:2 [
        "MONAT" => "AUG"
        "MAIL_CNT" => "2"
      ]
     1 => array:2 [
        "MONAT" => "JUL"
        "MAIL_CNT" => "1"
      ]
    ]

    array:2 [
      0 => array:2 [
        "MONAT" => "AUG"
        "ORDER_CNT" => "18"
      ]
      1 => array:2 [
        "MONAT" => "JUL"
        "ORDER_CNT" => "1"
      ]
    ]

结果应该是

array:1 [
      0 => array:2 [
        "MONAT" => "AUG"
        "MAIL_CNT" => "2"
        "ORDER_CNT" => "18"
      ]
     1 => array:2 [
        "MONAT" => "JUL"
        "MAIL_CNT" => "1"
        "ORDER_CNT" => "1"
      ]
    ]

我无法弄清楚该怎么做。

提前致谢和问候!

4 个答案:

答案 0 :(得分:1)

使用array_replace_recursive

$array = array_replace_recursive($a1, $a2);

答案 1 :(得分:1)

你应该使用php array_replace_recursive()来实现这个

$arr1=array(
    0 =>array(
        "MONAT" => "AUG",
        "MAIL_CNT" => "2"
    ),
    1 => array(
        "MONAT" => "JUL",
        "MAIL_CNT" => "1"
    )
);

$arr2=array(
    0 => array(
        "MONAT" => "AUG",
        "ORDER_CNT" => "18"
    ),
    1 => array(
        "MONAT" => "JUL",
        "ORDER_CNT" => "1"
    )
);

$array = array_replace_recursive($arr1, $arr2);
echo"<pre>"; print_r($array);

答案 2 :(得分:0)

$mergedArray = array();
foreach( $arr1 as $key => $row) {
    $mergedArray[$key] = array_merge($arr2[$key], $row)
}

希望这会有所帮助

答案 3 :(得分:0)

第一名:简单使用array_merge

第二名: &表示通过引用传递而不是value

foreach( $array1 as $key => &$val) {
   $val = array_merge($val,$array2[$key]);
}
print_r($array1);

注意:以上代码仅在both array count相同时才有效,否则会引发错误。