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 !

1
  • should your key MONAT match for both ? ts that the condition ? Commented Aug 1, 2017 at 10:05

4 Answers 4

6

use array_replace_recursive

$array = array_replace_recursive($a1, $a2);
Sign up to request clarification or add additional context in comments.

2 Comments

convincing but if the condition is month have to match and array length doesn't match both array then it will fail
Works like a charm! I feel a bit ashamed, i just tried array_replace :-)
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);

Comments

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

hope this helps

1 Comment

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.
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 .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.