-
-
Save kahwee/2688051 to your computer and use it in GitHub Desktop.
array_merge recursive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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