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

编程入门 行业动态 更新时间:2024-10-28 04:26:19
本文介绍了如何在 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 上的演示

除此之外,您唯一真正的选择是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 上的演示

更多推荐

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

本文发布于:2023-10-10 11:23:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1478526.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   如何在   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!