dtotwai720621 2016-01-13 07:59
浏览 115
已采纳

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

Its like this

I have a variable that has an array index in it, for e.g.

$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:

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(). 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. Its format is not fixed and only the script knows by the use of certain variables that what the array could be.

for e.g. at any point, the array might have an index $["xyz"][0]["abc"] which I want to access dynamically.

My php version is 5.1

  • 写回答

1条回答 默认 最新

  • douzhouqin6223 2016-01-13 08:10
    关注

    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. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

    In your case, $$var tries to read a variable with the name testVar["xyz"][0]["abc"], and not indexing an array. You could dereference that array like this:

    $a = "testVar";
    echo ${$a}["xyz"][0]["abc"];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加