How to use a string as an array index path to retrieve a value?
A Bit later, but... hope helps someone:
// $pathStr = "an:string:with:many:keys:as:path";
$paths = explode(":", $pathStr);
$itens = $myArray;
foreach($paths as $ndx){
$itens = $itens[$ndx];
}
Now itens is the part of the array you wanted to.
[]'s
Labs
you might use an array as path (from left to right), then a recursive function:
$indexes = {0, 'Data', 'name'};
function get_value($indexes, $arrayToAccess)
{
if(count($indexes) > 1)
return get_value(array_slice($indexes, 1), $arrayToAccess[$indexes[0]]);
else
return $arrayToAccess[$indexes[0]];
}
This is an old question but it has been referenced as this question comes up frequently.
There are recursive functions but I use a reference:
function array_nested_value($array, $path) {
$temp = &$array;
foreach($path as $key) {
$temp =& $temp[$key];
}
return $temp;
}
$path = array(0, 'Data', 'Name');
$value = array_nested_value($array, $path);
Try the following where $indexPath is formatted like a file path i.e.
'<array_key1>/<array_key2>/<array_key3>/...'.
function($indexPath, $arrayToAccess)
{
$explodedPath = explode('/', $indexPath);
$value =& $arrayToAccess;
foreach ($explodedPath as $key) {
$value =& $value[$key];
}
return $value;
}
e.g. using the data from the question, $indexPath = '1/Data/name/first' would return $value = Jane.
function($indexPath, $arrayToAccess)
{
eval('$return=$arrayToAccess'.$indexPath.';');
return $return;
}