如何在PHP的数组树中使用字符串? [英] How can I use a string within the tree of an array in PHP?
本文介绍了如何在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
有什么想法吗?
推荐答案
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!\n";
$path = "['boo']['far'][0]";
preg_match_all("/\['?([^\]']+)'?\]/", $path, $matches);
$v = $array;
foreach ($matches[1] as $p) {
$v = $v[$p];
}
echo $v;
输出:
hello world!
除此之外,您唯一真正的选择是 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!\n";
$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!
这篇关于如何在PHP的数组树中使用字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文