dongzhong7299 2016-01-28 05:53
浏览 153
已采纳

PHP变量变量和数组索引

I think this can be a simple problem for some of you. I've discovered similar questions, but they don't exactly solve my problem.

I've two arrays.

$array_numerals

Array
(
[2] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)

$array_two

Array
(
[0] => $100
[1] => $200
[2] => $300
)

If I use

echo $array_two[0];

it shows the output properly, which is $100, as expected.

what I want to do is to make the "two" and the "[0]" dynamic. the "two" can be replced with "three" or "four" while the "[0]" can be replaced with "[1]" or "[2]".

So if I use

$i = 2;
$j = 0;

echo $array_{$array_numerals[$i]}[$j];

it doesn't work and shows empty value.

Edit: Thank you all for the comments and answers. I must add that $array_two, $array_three, etc. are fixed variables given by another source, so it's not like I can control the initial construction of these arrays. Hence, the answers given by some of you won't work out of the box (not your fault of course, perhaps I didn't clarify enough in the beginning). The answers given by Amadan and LuvnJesus work the best.

  • 写回答

5条回答 默认 最新

  • doulv1760 2016-01-28 06:02
    关注
    echo ${"array_$array_numerals[$i]"}[$j];
    

    But I must warn you that it is a very bad idea to do this. Rather, use another lookup array:

    $array = Array(
      0 => Array(
        2 => "$100",
        ...
      ),
      ...
    );
    
    echo $array[$i][$j];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号