Skip to content
Advertisement

How can I merge array recursively with a unique key?

I create my arrays like this:

JavaScript

The result is array1:

JavaScript

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

JavaScript

Now I want to merge those arrays:

JavaScript

The output is:

JavaScript

But I expect the output to be:

JavaScript

Advertisement

Answer

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.

JavaScript

DEMO

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement