1

I have two n-dimensional arrays which I would like to merge. I have already reviewed this question, however, it is only good for merging two dimensional arrays. I am trying to accomplish the same thing, except with two n-dimensional arrays.

So, for example:

Array 1:

Array (
    [''] => 'ID One'
    ['foo'] => Array (
        [''] => 'ID Two'
        ['bar'] => 'ID Three'
    )
)

Array 2:

Array (
    ['foo'] => Array (
        ['bar'] => Array (
            ['baz'] => 'ID Four'
        )
    )
    ['bax'] => 'ID Five'
)

Desired Array Result:

Array (
    [''] => 'ID One'
    ['foo'] => Array (
        [''] => 'ID Two'
        ['bar'] => Array (
            [''] => 'ID Three'
            ['baz'] => 'ID Four'
        )
    )
    ['bax'] => 'ID Five'
)

Although this is a demonstration of what I am trying to achieve, when it is being used for some web apps, it is entirely possible that it will have 10, perhaps even 15 nested arrays. So, how can Array 1 and Array 2 be merged to form the Desired Array Result?

Community
  • 1
  • 1
topherg
  • 4,203
  • 4
  • 37
  • 72

2 Answers2

4

Conveniently, array_merge_recursive does exactly that!

This demo covers the cases.

Ry-
  • 218,210
  • 55
  • 464
  • 476
2

Try array_merge_recursive() or array_replace_recursive().

If neither of those functions does what you want, it's still easy to do with a recursive function, e.g.:

function merge($a, $b) {
    foreach ($b as $key => $value) {
        if (!is_array($value) {
            $a[$key] = $value;
        } else if (isset($a[$key])) {
            $a[$key] = merge($a[$key], $value);
        } else {
            $a[$key] = $value;
        }
    }
    return $a;
}

$merged = merge($a, $b);
Ry-
  • 218,210
  • 55
  • 464
  • 476
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194