php – How can I merge array recursively with a unique key?-ThrowExceptions

Exception or error:

I create my arrays like this:

foreach ($array as $key => $value) {
          $array1[$value->getUuid()][$value->getFields()->getName()] = $value->getContent();
        }

The result is array1:

array:2 [▼
  "d8ab80f4f6" => array:16 [▶]
  9087785727 => array:16 [▶]
]

I create another array in a little bit different way, array2:

array:2 [▼
  "d8ab80f4f6" => array:3 [▶]
  9087785727 => array:3 [▶]
]

Now I want to merge those arrays:

$output = array_merge_recursive($array1,$array2);

The output is:

array:3 [▼
  "d8ab80f4f6" => array:19 [▶]
  0 => array:3 [▶]
  1 => array:16 [▶]
]

But I expect the output to be:

array:3 [▼
  "d8ab80f4f6" => array:19 [▶]
  "9087785727" => array:19 [▶]
]
How to solve:

array_merge and array_merge_recursive treat string keys differently from numeric keys:

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

That’s what’s happening here. The key 9087785727 is numeric, so those entries are not being merged.

So you need to write your own loop.

$output = [];
foreach ($array1 as $key => $value) {
    $output[$key] = array_merge($value, $array2[$key]);
}

DEMO

Answer:

You can use next foreach loop with reference &:

foreach($ar1 as $key=>&$subar){
    $subar = array_merge($subar,$ar2[$key]); 
}

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *