note 109390 modified in function.array-replace-recursive by danbrown

From: 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:&#13;&#10;&#13;&#10;&#60;?php&#13;&#10;&#9;function array_replace_recursive($base, $replacements)&#13;&#10;&#9;{&#13;&#10;&#9;&#9;foreach (array_slice(func_get_args(), 1) as $replacements) {&#13;&#10;&#9;&#9;&#9;$bref_stack = array(&#38;$base);&#13;&#10;&#9;&#9;&#9;$head_stack = array($replacements);&#13;&#10;&#13;&#10;&#9;&#9;&#9;do {&#13;&#10;&#9;&#9;&#9;&#9;end($bref_stack);&#13;&#10;&#13;&#10;&#9;&#9;&#9;&#9;$bref = &#38;$bref_stack[key($bref_stack)];&#13;&#10;&#9;&#9;&#9;&#9;$head = array_pop($head_stack);&#13;&#10;&#13;&#10;&#9;&#9;&#9;&#9;unset($bref_stack[key($bref_stack)]);&#13;&#10;&#13;&#10;&#9;&#9;&#9;&#9;foreach (array_keys($head) as $key) {&#13;&#10;&#9;&#9;&#9;&#9;&#9;if (isset($key, $bref) &#38;&#38; is_array($bref[$key]) &#38;&#38; is_array($head[$key])) {&#13;&#10;&#9;&#9;&#9;&#9;&#9;&#9;$bref_stack[] = &#38;$bref[$key];&#13;&#10;&#9;&#9;&#9;&#9;&#9;&#9;$head_stack[] = $head[$key];&#13;&#10;&#9;&#9;&#9;&#9;&#9;} else {&#13;&#10;&#9;&#9;&#9;&#9;&#9;&#9;$bref[$key] = $head[$key];&#13;&#10;&#9;&#9;&#9;&#9;&#9;}&#13;&#10;&#9;&#9;&#9;&#9;}&#13;&#10;&#9;&#9;&#9;} while(count($head_stack));&#13;&#10;&#9;&#9;}&#13;&#10;&#13;&#10;&#9;&#9;return $base;&#13;&#10;&#9;}&#13;&#10;?&#62; --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

« previous php.notes (#189183) next »