1

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 !

WhiteRabbit
  • 322
  • 3
  • 12

4 Answers4

6

use array_replace_recursive

$array = array_replace_recursive($a1, $a2);
jiboulex
  • 2,963
  • 2
  • 18
  • 28
1

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);
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
0
$mergedArray = array();
foreach( $arr1 as $key => $row) {
    $mergedArray[$key] = array_merge($arr2[$key], $row)
}

hope this helps

jesuisgenial
  • 685
  • 1
  • 5
  • 15
  • While this method doesn't have a lot of moving parts to talk about, it is important to try to provide some explanation with answers and avoid code-only posts so that future SO readers are educated. – mickmackusa Aug 01 '17 at 12:38
0

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 .

JYoThI
  • 11,977
  • 1
  • 11
  • 26