dsxay48646 2018-05-15 01:36
浏览 19

PHP之间的动态变量名称

I have a badly designed Database that I have to deal with. In order to have a smaller code footprint, I need to use dynamic variable naming in PHP. However, the names of each variable vary greatly. Here's a sample of my code:

<?php

    $test = (object)[
        'variable_1_text'   => 'ONE',
        'variablevv_1_another_one'   => 'Two',
        'variablett_1_blah'   => 'III',
        'variablex_1_text_lala'   => 'Four',
        'variable_2_text'   => 'ONE',
        'variablevv_2_another_one'   => 'Two',
        'variablett_2_blah'   => 'III',
        'variablex_2_text_lala'   => 'Four',
        'variable_3_text'   => 'ONE',
        'variablevv_3_another_one'   => 'Two',
        'variablett_3_blah'   => 'III',
        'variablex_3_text_lala'   => 'Four',
        'variable_4_text'   => 'ONE',
        'variablevv_4_another_one'   => 'Two',
        'variablett_4_blah'   => 'III',
        'variablex_4_text_lala'   => 'Four',
    ];

    //this doesn't work
    foreach (array(1,2,3,4) as $temp_val) {
        echo $test->variable_{$temp_val}_text . "<br />";
        echo $test->variablevv_{$temp_val}_another_one . "<br />";
        echo $test->variablett_{$temp_val}_blah . "<br />";
        echo $test->variablex_{$temp_val}_text_lala . "<br />";
    }

?>

There's a lot of these variables. I just need how to dynamically make those 1, 2, 3, and 4 in between the names of the variable names. Is this even possible?

  • 写回答

1条回答 默认 最新

  • duanlinpi0265 2018-05-15 01:49
    关注

    You can try this: $test->{'variable_'.$temp_val.'_text'};

    评论

报告相同问题?

悬赏问题

  • ¥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 支付宝网页转账系统不识别账号