note 103396 added to function.array-merge-recursive
| From: | minghong at gmail dot com | Date: | Tue, 12 Apr 2011 04:49:27 +0000 |
| Subject: | note 103396 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-178718@lists.php.net to get a copy of this message | ||
There is one problem in bersace03's function: if the key value is an empty array, the key/value
will be gone after merging.
e.g.
Array A: array( 'a' => 123, 'b' => array() )
Array B: array( 'a' => 456 );
Expected result: array( 'a' => 456, 'b' => array() )
Actual result: array( 'a' => 456 )
A quick fix is to add $result[$key] = array();
The amended function becomes:
function array_merge_recursive_unique()
{
$arrays = func_get_args();
$remains = $arrays;
// We walk through each arrays and put value in the results (without
// considering previous value).
$result = array();
// loop available array
foreach ( $arrays as $array )
{
// The first remaining array is $array. We are processing it. So
// we remove it from remaing arrays.
array_shift( $remains );
// We don't care non array param, like array_merge since PHP 5.0.
if ( is_array($array) )
{
// Loop values
foreach ( $array as $key => $value )
{
if ( is_array($value) )
{
// We gather all remaining arrays that have such key available
$args = array();
foreach ( $remains as $remain )
{
if ( array_key_exists($key, $remain) )
{
array_push( $args, $remain[$key] );
}
}
$result[$key] = array();
if ( count($args) > 2 )
{
// Put the recursion
$result[$key] = call_user_func_array( __FUNCTION__, $args );
}
else
{
foreach ( $value as $vkey => $vval )
{
$result[$key][$vkey] = $vval;
}
}
}
else
{
// Simply put the value
$result[$key] = $value;
}
}
}
}
return $result;
}
----
Server IP: 59.188.18.107
Probable Submitter: 118.142.92.126
----
Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php
Edit -- https://master.php.net/note/edit/103396
Del: integrated -- https://master.php.net/note/delete/103396/integrated
Del: useless -- https://master.php.net/note/delete/103396/useless
Del: bad code -- https://master.php.net/note/delete/103396/bad+code
Del: spam -- https://master.php.net/note/delete/103396/spam
Del: non-english -- https://master.php.net/note/delete/103396/non-english
Del: in docs -- https://master.php.net/note/delete/103396/in+docs
Del: other reasons-- https://master.php.net/note/delete/103396
Reject -- https://master.php.net/note/reject/103396
Search -- https://master.php.net/manage/user-notes.php