note 91835 added to function.array-merge-recursive
| From: | jonnybergstrom at googlesmaildomain dot comm | Date: | Sat, 27 Jun 2009 15:30:20 +0000 |
| Subject: | note 91835 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-157630@lists.php.net to get a copy of this message | ||
This function didn't work for me - or it didn't do what I thought it would. So I wrote the
below function, which merges two arrays, and returns the resulting array. The base array is the left
one ($a1), and if a key is set in both arrays, the right value has precedence. If a value in the
left one is an array and also an array in the right one, the function calls itself (recursion). If
the left one is an array and the right one exists but is not an array, then the right
non-array-value will be used.
*Any key only appearing in the right one will be ignored*
- as I didn't need values appearing only in the right in my implementation, but if you want
that you could make some fast fix.
function array_merge_recursive_leftsource(&$a1, &$a2) {
$newArray = array();
foreach ($a1 as $key => $v) {
if (!isset($a2[$key])) {
$newArray[$key] = $v;
continue;
}
if (is_array($v)) {
if (!is_array($a2[$key])) {
$newArray[$key] = $a2[$key];
continue;
}
$newArray[$key] = array_merge_recursive_leftsource($a1[$key], $a2[$key]);
continue;
}
$newArray[$key] = $a2[$key];
}
return $newArray;
}
----
Server IP: 61.195.146.164
Probable Submitter: 122.29.31.114
----
Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php
Edit -- https://master.php.net/note/edit/91835
Del: integrated -- https://master.php.net/note/delete/91835/integrated
Del: useless -- https://master.php.net/note/delete/91835/useless
Del: bad code -- https://master.php.net/note/delete/91835/bad+code
Del: spam -- https://master.php.net/note/delete/91835/spam
Del: non-english -- https://master.php.net/note/delete/91835/non-english
Del: in docs -- https://master.php.net/note/delete/91835/in+docs
Del: other reasons-- https://master.php.net/note/delete/91835
Reject -- https://master.php.net/note/reject/91835
Search -- https://master.php.net/manage/user-notes.php