采用动态路径访问阵列 [英] Access array using dynamic path
本文介绍了采用动态路径访问阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在访问PHP中的数组的问题。
I have an issue in accessing the array in php.
$path = "['a']['b']['c']";
$value = $array.$path;
在上面这段code的我有一个名为$阵列的多维数组。
In the above piece of code I have an multidimensional array named $array.
$ PATH
是一个动态值,我就从数据库中获取。
$path
is a dynamic value which I would get from database.
现在我想用$路径检索$阵列的价值,但我不能。
Now I want to retrieve the value from $array using $path but I am not able to.
$value = $array.$path
返回我
Array['a']['b']['c']
而不是值
我希望我已经解释正确我的问题。
I hope I have explained my question properly.
推荐答案
您有两种选择。首先(邪恶),如果使用的eval()
功能 - 即跨preT的字符串的 code 的
You have two options. First (evil) if to use eval()
function - i.e. interpret your string as code.
二是要分析你的路径。这将是:
Second is to parse your path. That will be:
//$path = "['a']['b']['c']";
preg_match_all("/\['(.*?)'\]/", $path, $rgMatches);
$rgResult = $array;
foreach($rgMatches[1] as $sPath)
{
$rgResult=$rgResult[$sPath];
}
这篇关于采用动态路径访问阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文