Wie verwende ich eine Zeichenfolge als Array-Indexpfad, um einen Wert abzurufen?
Angenommen, ich habe ein Array wie:
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
)
)
)
)
Ich möchte in der Lage sein, eine Funktion zu erstellen, an die ich eine Zeichenfolge übergeben kann, die als Array-Indexpfad fungiert und den entsprechenden Array-Wert ohne Verwendung von zurückgibteval()
. Ist das möglich?
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 indexes 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 won't work
}