Jak użyć łańcucha jako ścieżki indeksu tablicy, aby pobrać wartość?
Powiedzmy, że mam tablicę taką jak:
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
)
)
)
)
Chcę być w stanie zbudować funkcję, do której mogę przekazać ciąg znaków, który będzie działał jako ścieżka indeksu tablicy i zwróci odpowiednią wartość tablicy bez użyciaeval()
. Czy to jest możliwe?
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
}