cooper cooper - 3 months ago 18
PHP Question

Trying to merge two multidimensional arrays and preserve keys

I need to merge two "three-dimensional" arrays but my problem is that when the first of the arrays keys is the same as the other, the result is just...not desirable.

An example here:

$a = array(
1=>array(
-1 => array(-1=>'a: 1 -1 -1',0=>'a: 1 -1 0',1=>'a: 1 -1 1'),
0 => array(-1=>'a: 1 0 -1', 0=>'a: 1 0 0', 1=>'a: 1 0 1'),
1 => array(-1=>'a: 1 1 -1', 0=>'a: 1 1 0', 1=>'a: 1 1 1')
)
);

$b = array(
1=>array(
1 => array(-1=>'b: 1 1 -1',0=>'b: 1 1 0',1=>'b: 1 1 1'),
2 => array(-1=>'b: 1 2 -1',0=>'b: 1 2 0',1=>'b: 1 2 1'),
3 => array(-1=>'b: 1 3 -1',0=>'b: 1 3 0',1=>'b: 1 3 1')
)
);


The result of doing $a + $b is:

Array
(
[1] => Array
(
[-1] => Array
(
[-1] => a: 1 -1 -1
[0] => a: 1 -1 0
[1] => a: 1 -1 1
)

[0] => Array
(
[-1] => a: 1 0 -1
[0] => a: 1 0 0
[1] => a: 1 0 1
)

[1] => Array
(
[-1] => a: 1 1 -1
[0] => a: 1 1 0
[1] => a: 1 1 1
)

)

)


And I need to say to PHP, "hey, the keys [1][2][X] and [1][3][X] in the 'b' array are not in the 'a' array, so merge them in the result".

I even don't care so much which one PHP is going to take when all the three keys are the same. The values of the keys are strings so I also not interested in sum that values. And I need to preserve the keys, so that a simple array_merge is not useful. Maybe I need to combine it with other function but I don't see which one.

Thanks in advance.

Tom Tom
Answer

You could try the array_replace_recursive function:

array_replace_recursive($a, $b);

The output looks like:

Array
(
    [1] => Array
        (
            [-1] => Array
                (
                    [-1] => a: 1 -1 -1
                    [0] => a: 1 -1 0
                    [1] => a: 1 -1 1
                )
            [0] => Array
                (
                    [-1] => a: 1 0 -1
                    [0] => a: 1 0 0
                    [1] => a: 1 0 1
                )
            [1] => Array
                (
                    [-1] => b: 1 1 -1
                    [0] => b: 1 1 0
                    [1] => b: 1 1 1
                )
            [2] => Array
                (
                    [-1] => b: 1 2 -1
                    [0] => b: 1 2 0
                    [1] => b: 1 2 1
                )
            [3] => Array
                (
                    [-1] => b: 1 3 -1
                    [0] => b: 1 3 0
                    [1] => b: 1 3 1
                )
        )
)

This will replace any entries with matching keys with the value in $b, so just double check if that's the outcome you desire (otherwise reverse $a and $b).

Comments