让说我有一个数组,如:如何使用字符串作为数组索引路径来检索值?
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