讓說我有一個數組,如:如何使用字符串作爲數組索引路徑來檢索值?
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
)
)
)
)
我希望能夠建立我可以通過一個字符串函數將作爲數組的索引路徑和不使用eval()
返回相應的數組值。那可能嗎?
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
}
不錯。注意複製和粘貼:遞歸調用'getValue'並不完全匹配函數名'get_value'。他們應該匹配才能正常工作。 – grossvogel 2010-06-01 17:07:29
這是現在修復的 – Ash 2012-10-30 11:12:29
這是一個很好的例子!謝謝@manji! – Michael 2014-10-25 16:47:20