Created
May 13, 2012 11:53
-
-
Save uzyn/2688024 to your computer and use it in GitHub Desktop.
array_merge recursive
This file contains hidden or 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
<?php | |
$a = array( | |
'asdf' => array( | |
'qqqq' => 'pppp', | |
'wwww' => 'oooo', | |
'eeee' => 'iiii' | |
), | |
'default' => 'yes' | |
); | |
$b = array( | |
'asdf' => array( | |
'qqqq' => 'a', | |
), | |
'default' => 'overwriten' | |
); | |
print_r(array_merge($a, $b)); | |
print_r(array_merge_recursive($a, $b)); | |
function merge($arr1, $arr2 = null) { | |
$args = func_get_args(); | |
$r = (array)current($args); | |
while (($arg = next($args)) !== false) { | |
foreach ((array)$arg as $key => $val) { | |
if (!empty($r[$key]) && is_array($r[$key]) && is_array($val)) { | |
$r[$key] = merge($r[$key], $val); | |
} elseif (is_int($key)) { | |
$r[] = $val; | |
} else { | |
$r[$key] = $val; | |
} | |
} | |
} | |
return $r; | |
} | |
print_r(merge($a, $b)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment