Alex Emilov Alex Emilov - 29 days ago 6
PHP Question

php recursive merge

I need to merge some arrays in some different way and I use array_merge_recursive.
However there is something that I need to change and I don't know how.
Here is quote from php.net


If, however, the arrays have the same numeric key, the later value
will not overwrite the original value, but will be appended.


I want this value, NOT to be appended, I want not to append exact values in the new array.Hope you've understood this.

Example:

$array = array(
'some' => array(
'other' => 'key',
),
);

$array2 = array();
$array2['some']['other'] = 'key2';


If I use array_merge_recursive It will result this:

Array (
[some] => Array
(
[other] => Array
(
[0] => key
[1] => key2
)
) )


I want if it matches the same result, not to append it.Yes I know, you would say, then use array_merge, but it doesn't work well, too.
If I use this:

$array = array(
'some' => array(
'other' => 'key',
),
);

$array2 = array();
$array2['some']['other2'] = 'key2';

print_r(array_merge($array, $array2));


It will remove $array[some][other] from the list and leave only $array[some][other2].I don't know which is better, since no one makes it better.

Answer

try this

<?php
function mymerge(&$a,$b){ //$a will be result. $a will be edited. It's to avoid a lot of copying in recursion
    foreach($b as $child=>$value){
        if(isset($a[$child])){ 
            if(is_array($a[$child]) && is_array($value)){ //merge if they are both arrays
                mymerge($a[$child],$value);
            }
            //else ignore, you can add your own logic, i.e when 1 of them is array
        }
        else
            $a[$child]=$value; //add if not exists
    }

    //return $a;
}