I have an interesting problem... I am building an API where user specifies the location of some element in an array through string. Like this:
$path = "group1.group2.group3.element";
Given this string, I must save some value to the correct place in an array. For the example above this would be:
$results['group1']['group2']['group3']['element'] = $value;
Of course, the code needs to be generic for whatever $path user throws at me.
How would you solve this?
UPDATE - SOLUTION: using both ern0's (similar to my own) and nikc's answer as inspiration, this is the solution I decided on:
// returns reference to node in $collection as referenced by $path. For example:
// $node =& findnode('dir.subdir', $some_array);
// In this case, $node points to $some_array['dir']['subdir'].
// If you wish to create the node if it doesn't exist, set $force to true
// (otherwise it throws exception if the node is not found)
function &findnode($path, &$collection, $force = false)
{
$parts = explode('.', $path);
$where = &$collection;
foreach ($parts as $part)
{
if (!isset($where[$part]))
{
if ($force)
$where[$part] = array();
else
throw new RuntimeException('path not found');
}
$where =& $where[$part];
}
return $where;
}
$results = array();
$value = '1';
try {
$bucket =& findnode("group1.group2.group3.element", $results, true);
} catch (Exception $e) {
// no such path and $force was false
}
$bucket = $value; // read or write value here
var_dump($results);
Thank you all for the answers, it was a nice exercise! :)
descendfunction which traversing the path step by step ultimately returns a reference to the correctnodeincollection.