php - 动态访问 PHP 数组

标签 php arrays

我尝试使用 $this->$arrDataName[$key] 访问数组 $this-> 中具有键 $key 的元素$arrDataName.但是 PHP 解释错误。

我在 $arrDataName$this->{$arrDataName}[$key] 周围用 { } 试过了,但是它不起作用。

在 php.net 上我找到了一个建议,但我无法实现。

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

也许任何人都可以帮助我。

谢谢!

编辑:

我觉得不行,但是我忘了填充数组。
最后它起作用了。 :)
这是解决方案:$this->{$arrDataName}[$key]

最佳答案

你的语法是正确的:

$this->{$varName}[$key]

你也可以为此使用一个额外的变量:

$myTempArr = $this->$arrDataName;

$myTempArr[ $key ];

恕我直言,那样可读性更好...

关于php - 动态访问 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3235632/

相关文章:

javascript - Searchfuntion 在 Symfony2 中使用 ajax 调用

arrays - 将数组中的所有项复制到引用类型的新数组中的函数

javascript - 是否可以在 Promise.all 稍后向数组添加 Promise?

php - 存储在 PHP 数组或 mySQL 中

php - MySQL float 被意外舍入

php - 为什么我们需要逃脱! < > : = - in php regular expressions?

php 在数组范围内查找值

javascript - 从 javaScript 数组中提取具有相同值的项目组

PHP Foreach 循环打印所有表情符号

php - 与在 PHP 中计算持续时间(然后存储在 MySQL 中)相比,在 MySQL 中计算持续时间有什么优势吗?