Skip to content

Instantly share code, notes, and snippets.

@kahwee
Forked from uzyn/gist:2688024
Created May 13, 2012 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kahwee/2688051 to your computer and use it in GitHub Desktop.
Save kahwee/2688051 to your computer and use it in GitHub Desktop.
array_merge recursive
class CMap2 {
/**
* Merges two or more arrays into one recursively.
* If each array has an element with the same string key value, the latter
* will overwrite the former (different from array_merge_recursive).
* Recursive merging will be conducted if both arrays have an element of array
* type and are having the same key.
* For integer-keyed elements, the elements from the latter array will
* be appended to the former array.
* @param array $a array to be merged to
* @param array $b array to be merged from. You can specifiy additional
* arrays via third argument, fourth argument etc.
* @return array the merged array (the original arrays are not changed.)
* @see mergeWith
*/
public static function mergeArray($a,$b)
{
$args=func_get_args();
$res=array_shift($args);
while(!empty($args))
{
$next=array_shift($args);
foreach($next as $k => $v)
{
if(is_integer($k))
isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
else if(is_array($v) && isset($res[$k]) && is_array($res[$k]))
$res[$k]=self::mergeArray($res[$k],$v);
else
$res[$k]=$v;
}
}
return $res;
}
}
$a = array(
'asdf' => array(
'qqqq' => 'pppp',
'wwww' => 'oooo',
'eeee' => 'iiii'
),
'default' => 'yes'
);
$b = array(
'asdf' => array(
'qqqq' => 'a',
),
'default' => 'overwriten'
);
var_dump(array_merge($a, $b));
var_dump(array_merge_recursive($a, $b));
var_dump(CMap2::mergeArray($a, $b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment