如何在 PHP 中的数组树中使用字符串? [英] How can I use a string within the tree of an array in PHP?

查看:37
本文介绍了如何在 PHP 中的数组树中使用字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取 PHP 中某个值的路径,但不确定如何将数组与字符串路径组合?下面给了我一个值.

I am getting the path to a value in PHP, but not sure how to combine the array with a stringed path? The following gives me a value.

var_dump($array['boo']['far'][0]); // works

虽然这些都没有给我一个有效的(甚至是有效的 PHP).

While none of these give me a valid (or are even valid PHP).

$path = "['boo']['far'][0]";
var_dump($array.$path); // doesn't work
var_dump($array{$path}); // doesn't work
var_dump(eval($array.$path)); // doesn't work

有什么想法吗?

推荐答案

如果路径的字符串组件相当简单,则可以使用 preg_match_all 然后递归遍历数组的各个级别以找到所需的元素:

If your string components of the path are fairly simple, you could parse the path into components using preg_match_all and then recursively go through the levels of the array to find the desired element:

$array['boo']['far'][0] = "hello world!
";
$path = "['boo']['far'][0]";

preg_match_all("/['?([^]']+)'?]/", $path, $matches);
$v = $array;
foreach ($matches[1] as $p) {
    $v = $v[$p];
}
echo $v;

输出:

hello world!

3v4l.org 上的演示

除此之外,您唯一真正的选择是eval.您可以使用 eval 来回显该值,或将其分配给另一个变量.例如,

Other than that, your only real alternative is eval. You can use eval to echo the value, or to assign it to another variable. For example,

$array['boo']['far'][0] = "hello world!
";
$path = "['boo']['far'][0]";
eval("echo $array$path;");
eval("$x = $array$path;");
echo $x;
$y = eval("return $array$path;");
echo $y;

输出:

hello world!
hello world!
hello world!

3v4l.org 上的演示

这篇关于如何在 PHP 中的数组树中使用字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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