note 106723 deleted from function.array-merge-recursive by danbrown
| From: | danbrown@php.net | Date: | Thu, 01 Dec 2011 21:51:01 +0000 |
| Subject: | note 106723 deleted from function.array-merge-recursive by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-184840@lists.php.net to get a copy of this message | ||
Note Submitter: jwege at acviti dot com
----
From walf's code, I just did 3 little changes:
- keep numbered keys as sometimes there is no need to reverse them to 0
- initialized $merged by the first array since there is no need to loop for that array
- stripped the "if (!$array) continue;" as this will be done by the foreach anyhow
Further I changed the example values a bit to make it more easy to understand for beginners (as I
am)
which values will survive and which came from what array: single digits from first, 4 digits from
second, larger from third
<?php
function lf_array_merge_recursive_add_or_overwrite()
{
if (func_num_args() < 2) {
trigger_error( __FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
return false;
}
$arrays = func_get_args();
$merged = array_shift($arrays);
while($arrays)
{
$array = array_shift($arrays);
if (!is_array($array))
{
trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
return false;
};
foreach ($array as $key => $value)
{
if (is_array($value) && array_key_exists($key, $merged) &&
is_array($merged[$key]))
{
$merged[$key] = call_user_func(__FUNCTION__, $merged[$key], $value);
}else{
$merged[$key] = $value;
};
};
};
return $merged;
};
$a1[88] = 1; // will stay
$a1['foo'] = 2;// will be overwritten and converted into array
$a1['bar'][] = 4;// will be overwritten and converted from array to num val
$a1['x'] = 5; // will stay
$a1['z'][] = 6; // will be overwritten
$a1['z']['m'] = 'hi'; // will be overwritten
$a1[100][] = 1; // will be overwritten
$a1[100]['xxx'] = 'a1 stay';// will stay
$a2[99] = 7000; // add
$a2['foo'][] = 8000; // overwrite, exists, convert from num to array
$a2['bar'] = 9000; // overwrite, coverting array into num val
$a2['y'] = 1000; // add
$a2['z']['m'] = 'bye'; // overwrite, exsts
$a2['z'][] = 2000; // overwrite, exists
$a3['z'][99] = 99999999; // add
$a3['z']['m'] = 'a3 ciao';// overwrite, exists
$a3[100][] = 5555555;// overwrite, exists
$a3[100]['yyy'] = 'a3 new one';// add
//print_r( $a1 );
//print_r( $a2 );
//print_r( $a3 );
echo "*++++ array_merge() now\n";
print_r( array_merge($a1, $a2, $a3) );
echo "*++++ array_merge_recursive_add_or_overwrite() follows\n";
print_r( lf_array_merge_recursive_add_or_overwrite($a1, $a2, $a3));
echo "*++++ array_merge_recursive() follows \n";
print_r( array_merge_recursive($a1, $a2, $a3));
?>