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)
?>