note 93905 added to function.array-merge-recursive
| From: | drvali at hotmail dot com | Date: | Tue, 06 Oct 2009 04:32:00 +0000 |
| Subject: | note 93905 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-161392@lists.php.net to get a copy of this message | ||
<?php
/**
* Merges any number of arrays of any dimensions, the later overwriting
* previous keys, unless the key is numeric, in whitch case, duplicated
* values will not be added.
*
* The arrays to be merged are passed as arguments to the function.
*
* @access public
* @return array Resulting array, once all have been merged
*/
function array_merge_replace_recursive() {
// Holds all the arrays passed
$params = & func_get_args ();
// First array is used as the base, everything else overwrites on it
$return = array_shift ( $params );
// Merge all arrays on the first array
foreach ( $params as $array ) {
foreach ( $array as $key => $value ) {
// Numeric keyed values are added (unless already there)
if (is_numeric ( $key ) && (! in_array ( $value, $return ))) {
if (is_array ( $value )) {
$return [] = $this->array_merge_replace_recursive ( $return [$$key], $value );
} else {
$return [] = $value;
}
// String keyed values are replaced
} else {
if (isset ( $return [$key] ) && is_array ( $value ) && is_array ( $return [$key]
)) {
$return [$key] = $this->array_merge_replace_recursive ( $return [$$key], $value );
} else {
$return [$key] = $value;
}
}
}
}
return $return;
}
$a = array (
"a" => 1,
"b" => 2,
'foo',
'bar'
);
$b = array (
"a" => 2,
"c" => 3,
'foo'
);
$c = array_merge_replace_recursive ( $a, $b );
print_r ( $a );
print_r ( $b );
print_r ( $c );
?>
Output:
Array
(
[a] => 1
[b] => 2
[0] => foo
[1] => bar
)
Array
(
[a] => 2
[c] => 3
[0] => foo
)
Array
(
[a] => 2
[b] => 2
[0] => foo
[1] => bar
[c] => 3
)
----
Server IP: 66.207.199.35
Probable Submitter: 74.57.169.98
----
Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php
Edit -- https://master.php.net/note/edit/93905
Del: integrated -- https://master.php.net/note/delete/93905/integrated
Del: useless -- https://master.php.net/note/delete/93905/useless
Del: bad code -- https://master.php.net/note/delete/93905/bad+code
Del: spam -- https://master.php.net/note/delete/93905/spam
Del: non-english -- https://master.php.net/note/delete/93905/non-english
Del: in docs -- https://master.php.net/note/delete/93905/in+docs
Del: other reasons-- https://master.php.net/note/delete/93905
Reject -- https://master.php.net/note/reject/93905
Search -- https://master.php.net/manage/user-notes.php