使用动态路径访问数组 [英] Access array using dynamic path

查看:43
本文介绍了使用动态路径访问数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 php 中访问数组时遇到问题.

I have an issue in accessing the array in php.

$path  = "['a']['b']['c']";
$value = $array.$path;

在上面的代码中,我有一个名为 $array 的多维数组.

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.

现在我想使用 $path 从 $array 中检索值,但我不能.

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() 函数 - 即把你的字符串解释为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆