note 104771 added to function.array-merge
| From: | eithedsthgmailsthcom at osu1 dot php dot net | Date: | Wed, 06 Jul 2011 14:03:21 +0000 |
| Subject: | note 104771 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-181287@lists.php.net to get a copy of this message | ||
I'm sorry, but I've not found on this page a function that would properly merge two arrays
while overwriting numeric values.
Considering two arrays:
$test1 = array(array('a','b','c'), 'a', 'b');
$test2 = array(array('d','e'), 'c');
while using overwrite merge you would expect the result to be an array:
$test3 = array(array('d','e'), 'c', 'b');
However most of the functions will result with this array:
$test4 = array(array('d','e','c'), 'c', 'b');
So, here's a function to do that:
function array_merge_overwrite(array &$array1, array $array2 = NULL)
{
$flag = true;
foreach (array_keys($array2) as $key)
{
if (isset($array2[$key]) && is_array($array2[$key]))
{
if (isset($array1[$key]) && is_array($array1[$key]))
array_merge_overwrite($array1[$key], $array2[$key]);
else
$array1[$key] = $array2[$key];
$flag = false;
}
}
if ($flag == true)
$array1 = $array2;
}
----
Server IP: 87.124.126.127
Probable Submitter: 86.164.250.28 (proxied: 86.164.250.28)
----
Manual Page -- http://www.php.net/manual/en/function.array-merge.php
Edit -- https://master.php.net/note/edit/104771
Del: integrated -- https://master.php.net/note/delete/104771/integrated
Del: useless -- https://master.php.net/note/delete/104771/useless
Del: bad code -- https://master.php.net/note/delete/104771/bad+code
Del: spam -- https://master.php.net/note/delete/104771/spam
Del: non-english -- https://master.php.net/note/delete/104771/non-english
Del: in docs -- https://master.php.net/note/delete/104771/in+docs
Del: other reasons-- https://master.php.net/note/delete/104771
Reject -- https://master.php.net/note/reject/104771
Search -- https://master.php.net/manage/user-notes.php