note 106340 added to function.array-walk-recursive

From: Date: Sat, 29 Oct 2011 02:45:29 +0000
Subject: note 106340 added to function.array-walk-recursive
Groups: php.notes 
Request: Send a blank email to php-notes+get-184209@lists.php.net to get a copy of this message
I needed to add or modify values in an array with unknown structure. I was hoping to use array_walk_recursive for the task, but because I was also adding new nodes I came up with an alternate solution. <?php /** * Sets key/value pairs at any depth on an array. * @param $data an array of key/value pairs to be added/modified * @param $array the array to operate on */ function setNodes($data, &$array) { $separator = '.'; // set this to any string that won't occur in your keys foreach ($data as $name => $value) { if (strpos($name, $separator) === false) { // If the array doesn't contain a special separator character, just set the key/value pair. // If $value is an array, you will of course set nested key/value pairs just fine. $array[$name] = $value; } else { // In this case we're trying to target a specific nested node without overwriting any other siblings/ancestors. // The node or its ancestors may not exist yet. $keys = explode($separator, $name); // Set the root of the tree. $opt_tree =& $array; // Start traversing the tree using the specified keys. while ($key = array_shift($keys)) { // If there are more keys after the current one... if ($keys) { if (!isset($opt_tree[$key]) || !is_array($opt_tree[$key])) { // Create this node if it doesn't already exist. $opt_tree[$key] = array(); } // Redefine the "root" of the tree to this node (assign by reference) then process the next key. $opt_tree =& $opt_tree[$key]; } else { // This is the last key to check, so assign the value. $opt_tree[$key] = $value; } } } } } ?> Sample usage: <?php $x = array(); setNodes(array('foo' => 'bar', 'baz' => array('quux' => 42, 'hup' => 101)), $x); print_r($x); // $x has the same structure as the first argument setNodes(array('jif.snee' => 'hello world', 'baz.quux.wek' => 5), $x); print_r($x); // added $x['jif']['snee'] and modified $x['baz']['quux'] to be array('wek' => 5) ?> ---- Server IP: 216.235.13.26 Probable Submitter: 24.68.105.213 ---- Manual Page -- http://www.php.net/manual/en/function.array-walk-recursive.php Edit -- https://master.php.net/note/edit/106340 Del: integrated -- https://master.php.net/note/delete/106340/integrated Del: useless -- https://master.php.net/note/delete/106340/useless Del: bad code -- https://master.php.net/note/delete/106340/bad+code Del: spam -- https://master.php.net/note/delete/106340/spam Del: non-english -- https://master.php.net/note/delete/106340/non-english Del: in docs -- https://master.php.net/note/delete/106340/in+docs Del: other reasons-- https://master.php.net/note/delete/106340 Reject -- https://master.php.net/note/reject/106340 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#184209) next »