我正在用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!\n"; $path = "['boo']['far'][0]"; preg_match_all("/\['?([^\]']+)'?\]/", $path, $matches); $v = $array; foreach ($matches[1] as $p) { $v = $v[$p]; } echo $v;输出:
hello world!在3v4l上进行演示
除此之外,您唯一真正的选择是 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!在3v4l上进行演示
更多推荐
如何在PHP的数组树中使用字符串?
发布评论