I was just reminded to post my final version of the function I wrote to merge two arrays in the way I needed it.
<?php
function merge(&$a, &$b){
if(is_array($a) and is_array($b)){
if(isset($a[0])){ # $a is a numeric array, so copy b straight over it
$a = $b;
}
$keys = array_keys($a);
foreach($keys as $key){
if(isset($b[$key])){
if(is_array($a[$key]) and is_array($b[$key])){
merge($a[$key],$b[$key]);
}else{
$a[$key] = $b[$key];
}
}
}
$keys = array_keys($b);
foreach($keys as $key){
if(!isset($a[$key])){
$a[$key] = $b[$key];
}
}
}else{
$a = $b;
}
}
?>
This merges two arrays key for key, recursively, unless array $a is a plain old numeric array rather than an associative array, in which case it overwrites array $a with array $b. If a key exists in both arrays (and the value is a scalar, instead of another array, in which case it would recurse), it overwrites the value in array $a with the value from array $b. If $a and $b aren't both arrays, then $a is overwritten by $b.
Feel free to post a comment below. Please see my comment policy.
Formatting Rules (No HTML):