note 92224 modified in function.array-replace-recursive by danbrown
| From: | danbrown@php.net | Date: | Tue, 14 Jul 2009 23:45:18 +0000 |
| Subject: | note 92224 modified in function.array-replace-recursive by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158314@lists.php.net to get a copy of this message | ||
This might help out people who don't have 5.3 running:
<?php
// Joins two or more arrays together recursively; key/value pairs of the first
// array are replaced with key/value pairs from the subsequent arrays. Any
// key/value pair not present in the first array is added to the final array
function array_join()
{
// Get array arguments
$arrays = func_get_args();
// Define the original array
$original = array_shift($arrays);
// Loop through arrays
foreach ($arrays as $array)
{
// Loop through array key/value pairs
foreach ($array as $key => $value)
{
// Value is an array
if (is_array($value))
{
// Traverse the array; replace or add result to original array
$original[$key] = array_join($original[$key], $array[$key]);
}
// Value is not an array
else
{
// Replace or add current value to original array
$original[$key] = $value;
}
}
}
// Return the joined array
return $original;
}
?>
--was--
Function corrected from below:
<?
// Joins two or more arrays together recursively; key/value pairs of the first
// array are replaced with key/value pairs from the subsequent arrays. Any
// key/value pair not present in the first array is added to the final array
function array_join()
{
// Get array arguments
$arrays = func_get_args();
// Define the original array
$original = array_shift($arrays);
// Loop through arrays
foreach ($arrays as $array)
{
// Loop through array key/value pairs
foreach ($array as $key => $value)
{
// Value is an array
if (is_array($value))
{
// Traverse the array; replace or add result to original array
$original[$key] = array_join($original[$key], $array[$key]);
}
// Value is not an array
else
{
// Replace or add current value to original array
$original[$key] = $value;
}
}
}
// Return the joined array
return $original;
}
?>
http://php.net/manual/en/function.array-replace-recursive.php