如何在 PHP 中的数组树中使用字符串?

2022-01-05 00:00:00 arrays tree 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 上的演示

相关文章