PHP 中变量的数组路径
因此,我编写了一个类,它可以解析 XML 文档并从中创建 SQL 查询,以根据设置更新或插入新行。
由于脚本必须处理任意数量的嵌套块,因此我放入所有值的数组的路径是动态创建的,与以下示例非常相似:
$path = array('field1','field2');
$path = "['".implode("']['",$path)."']";
eval("\$array".$path."['value'] = 'test';");
基本上 $path
包含一个显示的数组如果 $path
包含例如值 main_table
和 field
我想设置 $array[ 'main_table']['field']['value']
到 'test'
如您所见,我目前正在使用 eval 来执行此操作,并且效果很好。我只是想知道是否有一种方法可以在不使用 eval 的情况下做到这一点。
像这样的东西 $array{$path}['value'] = 'test';
但实际上是有效的。
有什么建议吗?
编辑
我正在寻找替代方案的原因是因为我认为 eval 是不好的做法。
第二次编辑
将实际代码更改为虚拟代码,因为它引起了很多误解。
So I wrote a class that can parse XML documents and create SQL queries from it to update or insert new rows depending on the settings.
Because the script has to work with any amount of nested blocks, the array that I'm putting all the values in has its path dynamically created much like the following example:
$path = array('field1','field2');
$path = "['".implode("']['",$path)."']";
eval("\$array".$path."['value'] = 'test';");
Basically $path
contains an array that shows how deep in the array we currently are, if $path
contains for instance the values main_table
and field
I want set $array['main_table']['field']['value']
to 'test'
As you can see I am currently using eval to do this, and this works fine. I am just wondering if there is a way to do this without using eval.
Something like$array{$path}['value'] = 'test';
but then something that actually works.
Any suggestions?
EDIT
The reason I'm looking for an alternative is because I think eval is bad practice.
SECOND EDIT
Changed actual code to dummy code because it was causing a lot of misunderstandings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用这样的东西:
Use something like this:
您可以使用数组追加运算符绕过整个计数器业务:
至于整个路径业务,我假设这基本上是通过您的 xml 文档的类似 xpath 的路线的奇怪表示...您不能简单地使用的任何原因该字符串本身作为数组键?
You can bypass the whole counter business with the array append operator:
As for the whole path business, I'm assuming that's basically an oddball representation of an xpath-like route through your xml document... any reason you can't simply use that string as an array key itself?
您可以将 foreach 与 变量 结合使用。
简短、简单,并且比 eval 好得多。
You can use a foreach with variable variables.
Short, simple, and much better than eval.