Created
January 8, 2010 08:28
-
-
Save hugowetterberg/271920 to your computer and use it in GitHub Desktop.
A less useless recursive merge of arrays
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 | |
/* | |
* As you probably know array_merge_recursive() is pretty useless. This is a function | |
* that I always tend to write when working with recursive merges of arrays. | |
* | |
* See output.txt to see the difference in behaviour. | |
*/ | |
function custom_merge_recursive(/* $a, $b, $c, ... */) { | |
$args = func_get_args(); | |
$a = array_shift($args); | |
foreach ($args as $b) { | |
foreach ($b as $key => $val) { | |
if (is_array($val) && is_array($a[$key])) { | |
$b[$key] = custom_merge_recursive($a[$key], $val); | |
} | |
} | |
$a = array_merge($a, $b); | |
} | |
return $a; | |
} | |
$defaults = array( | |
'pageOffset' => 0, | |
'itemsPerPage' => 10, | |
'filter' => array( | |
'OrderBy' => 'None', | |
'SortOrder' => 'Descending', | |
'SubCategoryId' => 0, | |
), | |
); | |
echo "//-- Result with array_merge_recursive\n"; | |
var_dump(array_merge_recursive($defaults, array( | |
'pageOffset' => 2, | |
'filter' => array( | |
'SubCategoryId' => 10, | |
), | |
), | |
array( | |
'itemsPerPage' => 20, | |
))); | |
echo "\n//-- Result with custom_merge_recursive\n"; | |
var_dump(custom_merge_recursive($defaults, array( | |
'pageOffset' => 2, | |
'filter' => array( | |
'SubCategoryId' => 10, | |
), | |
), | |
array( | |
'itemsPerPage' => 20, | |
))); |
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
//-- Result with array_merge_recursive | |
array(3) { | |
["pageOffset"]=> | |
array(2) { | |
[0]=> | |
int(0) | |
[1]=> | |
int(2) | |
} | |
["itemsPerPage"]=> | |
array(2) { | |
[0]=> | |
int(10) | |
[1]=> | |
int(20) | |
} | |
["filter"]=> | |
array(3) { | |
["OrderBy"]=> | |
string(4) "None" | |
["SortOrder"]=> | |
string(10) "Descending" | |
["SubCategoryId"]=> | |
array(2) { | |
[0]=> | |
int(0) | |
[1]=> | |
int(10) | |
} | |
} | |
} | |
//-- Result with custom_merge_recursive | |
array(3) { | |
["pageOffset"]=> | |
int(2) | |
["itemsPerPage"]=> | |
int(20) | |
["filter"]=> | |
array(3) { | |
["OrderBy"]=> | |
string(4) "None" | |
["SortOrder"]=> | |
string(10) "Descending" | |
["SubCategoryId"]=> | |
int(10) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment