note 92195 added to function.array-merge-recursive
| From: | gabriel dot sobrinho at gmail dot com | Date: | Tue, 14 Jul 2009 02:56:31 +0000 |
| Subject: | note 92195 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158256@lists.php.net to get a copy of this message | ||
I refactored the Daniel's function and I got it:
<?php
/**
* array_merge_recursive does indeed merge arrays, but it converts values with duplicate
* keys to arrays rather than overwriting the value in the first array with the duplicate
* value in the second array, as array_merge does. I.e., with array_merge_recursive,
* this happens (documented behavior):
*
* array_merge_recursive(array('key' => 'org value'), array('key'
=> 'new value'));
* => array('key' => array('org value', 'new value'));
*
* array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
* Matching keys' values in the second array overwrite those in the first array, as is the
* case with array_merge, i.e.:
*
* array_merge_recursive_distinct(array('key' => 'org value'),
array('key' => 'new value'));
* => array('key' => array('new value'));
*
* Parameters are passed by reference, though only for performance reasons. They're not
* altered by this function.
*
* @param array $array1
* @param array $array2
* @return array
* @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
* @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
*/
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
$merged = $array1;
foreach ( $array2 as $key => &$value )
{
if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged
[$key] ) )
{
$merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
}
else
{
$merged [$key] = $value;
}
}
return $merged;
}
?>
This fix the E_NOTICE when the the first array doesn't have the key and the second array have a
value which is a array.
----
Server IP: 187.16.23.134
Probable Submitter: 187.20.112.25
----
Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php
Edit -- https://master.php.net/note/edit/92195
Del: integrated -- https://master.php.net/note/delete/92195/integrated
Del: useless -- https://master.php.net/note/delete/92195/useless
Del: bad code -- https://master.php.net/note/delete/92195/bad+code
Del: spam -- https://master.php.net/note/delete/92195/spam
Del: non-english -- https://master.php.net/note/delete/92195/non-english
Del: in docs -- https://master.php.net/note/delete/92195/in+docs
Del: other reasons-- https://master.php.net/note/delete/92195
Reject -- https://master.php.net/note/reject/92195
Search -- https://master.php.net/manage/user-notes.php