dtotwai720621
dtotwai720621
2016-01-13 07:59

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

  • eval
  • php
  • arrays

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条回答