note 38387 added to function.array-merge-recursive
| From: | shemari75 at mixmail dot com | Date: | Fri, 19 Dec 2003 02:22:19 +0000 |
| Subject: | note 38387 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-62199@lists.php.net to get a copy of this message | ||
Here's a function to recursively merge any number of any-dimensional arrays.
It actually works in quite a similar way as array_merge_recursive does, but with two major
differences:
- Later elements overwrite previous ones having the same keys.
- Numeric keys are not appended. Instead, they are converted into associative ones, and therefore
overwritten as stated above.
Usage:
array array_merge_n(array array1, array array2[, array ...])
<?php
/**
* Merges two arrays of any dimension
*
* This is the process' core!
* Here each array is merged with the current resulting one
*
* @access private
* @author Chema Barcala Calveiro <shemari75@mixmail.com>
* @param array $array Resulting array - passed by reference
* @param array $array_i Array to be merged - passed by reference
*/
function array_merge_2(&$array, &$array_i) {
// For each element of the array (key => value):
foreach ($array_i as $k => $v) {
// If the value itself is an array, the process repeats recursively:
if (is_array($v)) {
if (!isset($array[$k])) {
$array[$k] = array();
}
array_merge_2($array[$k], $v);
// Else, the value is assigned to the current element of the resulting array:
} else {
if (isset($array[$k]) && is_array($array[$k])) {
$array[$k][0] = $v;
} else {
if (isset($array) && !is_array($array)) {
$temp = $array;
$array = array();
$array[0] = $temp;
}
$array[$k] = $v;
}
}
}
}
/**
* Merges any number of arrays of any dimension
*
* The arrays to be merged are passed as arguments to the function,
* which uses an external function (array_merge_2) to merge each of them
* with the resulting one as it's being constructed
*
* @access public
* @author Chema Barcala Calveiro <shemari75@mixmail.com>
* @return array Resulting array, once all have been merged
*/
function array_merge_n() {
// Initialization of the resulting array:
$array = array();
// Arrays to be merged (function's arguments):
$arrays =& func_get_args();
// Merging of each array with the resulting one:
foreach ($arrays as $array_i) {
if (is_array($array_i)) {
array_merge_2($array, $array_i);
}
}
return $array;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+38387
Delete -- http://master.php.net/manage/user-notes.php?action=delete+38387&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+38387&report=yes
Search -- http://master.php.net/manage/user-notes.php