【问题标题】:Dynamically setting a variable in PHP?在 PHP 中动态设置变量?
【发布时间】:2010-11-06 15:49:00
【问题描述】:

所以我想解决这样的问题,但不知道如何

    for($s=0; $s < 5; $s++ ){
      $pre_config_query = "select * from preconfig where code = '{$industry_string}_{$s}_{$class_string}'";
      $pre_config_station = mysql_query($pre_config_query);
      $it_exists = mysql_num_rows($pre_config_station);
      if($it_exists>0){
        $pre_config = mysql_fetch_assoc($pre_config_station);
        $pre{$s} = $pre_config['id']; 

我希望最终产品将这 5 个变量命名为

    print $pre1;
    print $pre2;
    print $pre3;
    print $pre4;
    print $pre5;

如果有 $pre_config['id'] 的话......任何想法

【问题讨论】:

  • 为什么不直接使用数组或者关联数组呢?事实上,无论您计划什么,它都可能会变得更容易。

标签: php variables loops


【解决方案1】:

您可以使用variable variables 来完成此操作。

首先,定义一个具有所需名称的变量:

$varname = "pre$s";

其次,给它赋值:

$$varname = $pre_config['id'];

就是这样!

【讨论】:

    【解决方案2】:

    这可行,但我不确定我是否在回答你的问题。

    <?php
    for($s=1; $s < 6; $s++ ){
        $it_exists=1;
          if($it_exists > 0){
            $pre_config = array('id'=>rand(10,99));
            ${"pre".$s} = $pre_config['id'];
          }
    }
    echo $pre1."<br/>";
    echo $pre2."<br/>";
    echo $pre3."<br/>";
    echo $pre4."<br/>";
    echo $pre5."<br/>";
    

    ?>

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 2019-12-23
      • 2014-12-09
      • 2019-08-31
      • 1970-01-01
      • 2017-01-12
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多