简体   繁体   English

php:使用字符串变量动态访问数组

[英]php: accessing array dynamically using a string variable

Its like this 就像这样

I have a variable that has an array index in it, for eg 我有一个具有数组索引的变量,例如

$var = 'testVar["abc"][0]';

or 要么

$var = 'testVar["xyz"][0]["abc"]';

or it could be anything at run time. 或者在运行时可以是任何东西。

Now when I try to access this by using this php code: 现在,当我尝试使用以下php代码访问此文件时:

echo $$var;

or 要么

echo ${$var};

I get a warning saying Illegal offset at line ... 我收到一条警告,说在行上有非法的偏移量...

but if I use this code, it works 但是如果我使用此代码,它就可以工作

eval('echo $'.$var);

I do not want to use eval(). 我不想使用eval()。 Is there any other way? 还有其他办法吗?

EDIT: 编辑:

The variable $testVar is an array build up on runtime and it could have multi-dimensional array built dynamically. 变量$ testVar是在运行时建立的数组,它可以动态构建多维数组。 Its format is not fixed and only the script knows by the use of certain variables that what the array could be. 它的格式不是固定的,只有脚本通过使用某些变量才能知道数组可能是什么。

for eg at any point, the array might have an index $["xyz"][0]["abc"] which I want to access dynamically. 例如,在任何时候,数组可能都有一个索引$["xyz"][0]["abc"] ,我想动态地访问它。

My php version is 5.1 我的PHP版本是5.1

According to the documentation , what you are trying to accomplish is not possible: 根据文档 ,您要完成的任务是不可能的:

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. 也就是说,如果您编写$$a[1]则解析器需要知道您是要使用$a[1]作为变量,还是要使用$$a作为变量,然后从[1]索引该变量。 The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second. 解决这种歧义的语法是:第一种情况为${$a[1]} ,第二种情况${$a}[1]

In your case, $$var tries to read a variable with the name testVar["xyz"][0]["abc"] , and not indexing an array. 在您的情况下, $$var尝试读取名称为testVar["xyz"][0]["abc"]的变量,但不索引数组。 You could dereference that array like this: 您可以像这样取消引用该数组:

$a = "testVar";
echo ${$a}["xyz"][0]["abc"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM