简体   繁体   中英

PHP Merge Array and keep key

i want to join two arrays where 1 key should join them.

    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"
      ]
    ]

The result should be something like

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

I cant figure out what to do.

Thanks in advance and greetings !

使用array_replace_recursive

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

you should use php array_replace_recursive() for this

$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);
$mergedArray = array();
foreach( $arr1 as $key => $row) {
    $mergedArray[$key] = array_merge($arr2[$key], $row)
}

hope this helps

1st : simple use array_merge

2nd : & means it is passed by reference instead of value

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

Note : Above code will work only if both array count is same otherwise it will throw the error .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM