如何使用字符串作为数组索引路径检索值? [英] How to use a string as an array index path to retrieve a value?
本文介绍了如何使用字符串作为数组索引路径检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让说我有这样一个数组:
阵列
(
[0] =>排列
(
[数据] =>排列
(
[ID] => 1
[标题] =>经理
[名] =>约翰·史密斯
)
)
[1] =>排列
(
[数据] =>排列
(
[ID] => 1
[标题] =>书记
[名] =>
(
[首页] =>简
[最后] =>工匠
)
) ))
我希望能够建立我可以通过一个字符串将作为数组的索引路径,并且不使用的eval()
。这可能吗?
函数($ indexPath,$ arrayToAccess)
{
// $ indexPath会是这样的[0] ['数据'] ['名']这将返回
//经理人或者它可以[1] ['数据'] ['名'] ['第一']这将返回
//简,但会在索引路径数组索引量能
//变化,所以有可能是3,如第一个例子,或4类似的第二个。 返回$ arrayToAccess [$ indexPath] //< - 显然是行不通的
}
解决方案
您可以使用数组作为路径(从左至右),那么递归函数:
$指数= {0,'数据','名'};功能的get_value($索引,$ arrayToAccess)
{
如果(计数($索引)→1)
返回的get_value(array_slice($索引,1),$ arrayToAccess [$索引[0]);
其他
返回$ arrayToAccess [$索引[0]];
}
Let 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 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
}
解决方案
you might use an array as path (from left to right), then a recursive function:
$indexes = {0, 'Data', 'name'};
function get_value($indexes, $arrayToAccess)
{
if(count($indexes) > 1)
return get_value(array_slice($indexes, 1), $arrayToAccess[$indexes[0]]);
else
return $arrayToAccess[$indexes[0]];
}
这篇关于如何使用字符串作为数组索引路径检索值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文