到PHP数组动态访问 [英] Dynamic access to a PHP array
问题描述
我试着用 $这个 - &GT访问; $ arrDataName [$关键]
的关键元素上 $键
从数组 $这个 - > $ arrDataName
。但是PHP间preTES那个做错了。
I tried to access with $this->$arrDataName[$key]
on the element with the key $key
from the array $this->$arrDataName
. But PHP interpretes that wrong.
我试了一下 {}
围绕 $ arrDataName
到 $这个 - &GT ; {$ arrDataName} [$键]
,但它不能正常工作
I tried it with { }
around the $arrDataName
to $this->{$arrDataName}[$key]
, but it doesn't work.
在php.net我发现了一个建议,但我没有意识到这一点。
On php.net I found an advice, but I can't realize it.
为了使用可变变量与数组,必须解决一个模棱两可的问题。也就是说,如果你写$$ a [1],解析器需要知道,如果你想用一个$ [1]作为一个变量,或者如果你想$$ a作为变量,然后在[1]从指数该变量。解决这种模棱两可的语法为:$ {$ a [1]}对于第一种情况和$ {$ A} [1]第二个
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.
也许有人能帮助我。
谢谢!
编辑:
我认为这是行不通的,但我忘了,填补了数组。结果
最后,它的工作原理。 :)结果
这是解决方案: $这个 - > {$ arrDataName} [$键]
I think it doesn't work, but I forgot to fill the array.
Finally it works. :)
This is the solution: $this->{$arrDataName}[$key]
推荐答案
您的语法是正确的:
$this->{$varName}[$key]
您也可以使用一个额外的变量此:
You can also use an extra variable for this:
$myTempArr = $this->$arrDataName;
$myTempArr[ $key ];
恕我直言,可读性更好的这样...
IMHO, readability is better that way...
这篇关于到PHP数组动态访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!