note 109390 modified in function.array-replace-recursive by danbrown
| From: | danbrown@php.net | Date: | Mon, 16 Jul 2012 15:34:21 +0000 |
| Subject: | note 109390 modified in function.array-replace-recursive by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189183@lists.php.net to get a copy of this message | ||
This is a fairly concise version which does not rely on traditional
recursion: <?php 	function
array_replace_recursive($base,
$replacements) 	{ 		foreach
(array_slice(func_get_args(), 1) as $replacements)
{ 			$bref_stack =
array(&$base); 			$head_stack =
array($replacements); 			do
{ 				end($bref_stack); 				$bref
= &$bref_stack[key($bref_stack)]; 				$head =
array_pop($head_stack); 				unset($bref_stack[key($bref_stack)]); 				foreach
(array_keys($head) as $key) { 					if
(isset($key, $bref) && is_array($bref[$key]) &&
is_array($head[$key]))
{ 						$bref_stack[] =
&$bref[$key]; 						$head_stack[]
= $head[$key]; 					} else
{ 						$bref[$key] =
$head[$key]; 					} 				} 			}
while(count($head_stack)); 		} 		return
$base; 	} ?>
--was--
This is a fairly concise version which does not rely on traditional recursion:
<?php
function array_replace_recursive($base, $replacements)
{
foreach (array_slice(func_get_args(), 1) as $replacements) {
$bref_stack = array(&$base);
$head_stack = array($replacements);
do {
end($bref_stack);
$bref = &$bref_stack[key($bref_stack)];
$head = array_pop($head_stack);
unset($bref_stack[key($bref_stack)]);
foreach (array_keys($head) as $key) {
if (isset($key, $bref) && is_array($bref[$key]) && is_array($head[$key])) {
$bref_stack[] = &$bref[$key];
$head_stack[] = $head[$key];
} else {
$bref[$key] = $head[$key];
}
}
} while(count($head_stack));
}
return $base;
}
http://php.net/manual/en/function.array-replace-recursive.php