如何动态引用 php ARRAY 变量?
大家都知道可以使用 ${'varName'} 访问 PHP 中的变量。但是,当您需要获取/设置一个属于数组一部分的变量时,为什么它不起作用?假设我们有这段代码:
<?php
$myArray = array(...);
$myVarName = "myArray['my1']['my11']['my111']";
${$myVarName} = "new value";
?>
它不应该工作吗? 我已经一次又一次地测试过它 - 它不起作用.. 有办法做到这一点吗?
Everybody knows that you can access a variable in PHP using this: ${'varName'}. But when you need to get/set a variable witch is part of an array, why doesn't it work ? Suppose we have this piece of code:
<?php
$myArray = array(...);
$myVarName = "myArray['my1']['my11']['my111']";
${$myVarName} = "new value";
?>
Shouldn't it work ?
I have tested it again and again - it is not working..
Is it there a way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您不要使用像
${$var}
这样的动态变量。您想要的是根据键的路径修改多维关联数组。
为了简单起见,这是一个程序示例。您可能希望将分层数组和此函数放入一个类中。
I recommend you not to use dynamic variables like
${$var}
.What you want is modifying a multi-dimensional associative array according to a path of keys.
This is a procedural example to keep it simple. You may want to put your hierarchical array and this functions inside a class.
不。
是的。但每个人都知道这是蹩脚的。
拥有
('my1','my11','my111')
数组,您可以仅使用循环来引用任何特定的数组成员。No.
Yes. Yet everybody knows that's lame.
having array of
('my1','my11','my111')
you can refer to any particular array member using merely a loop.你可以做这样的事情,但这将是一个非常糟糕的主意。对不起上校;)
You could do something like this, but it would be a really bad idea. Sorry Col. ;)