PHP: Use a string as an array index path to retreive a value.
- by Charles
Say I have an array like:
Array
(
[0] => Array
(
[Data] => Array
(
[id] => 1
[title] => Manager
[name] => John Smith
)
)
[1] => Array
(
[Data] => Array
(
[id] => 1
[title] => Clerk
[name] =>
(
[first] => Jane
[last] => Smith
)
)
)
)
I want to be able to build a function that I can pass a string to that will act as the array index path and return the appropriate array value without using eval(). Is that possible?
function($indexPath, $arrayToAccess)
{
//$indexPath would be something like [0]['Data']['name'] which would return
//"Manager" or it could be [1]['Data']['name']['first'] which would return
//"Jane" but the amount of array indexs that will be in the index path can
//change, so there might be 3 like the first example, or 4 like the second.
return $arrayToAccess[$indexPath] <-obviously wont work
}