douzi1117 2016-11-16 21:36
浏览 34
已采纳

把一个计数器放在变量的名称上[重复]

This question already has an answer here:

What I wanna do is take the variable name $ingreso and increment it at the end to send a lot of variables with the same name but with a different number at the end,$ingreso1, ingreso2 etc, but I don't know how to concatenate it correctly. Please Help.

PHP Code:

 while ( $cont<= 15){           
      $sql = "INSERT INTO ingreso (vlr_ingreso, periodo_ingreso, proyecto_id_proyecto)
              VALUES ('$ingreso".$cont."','$cont','$proyecto_id');";
      $insert = mysqli_query($con, $sql);
    }

But it keeps returning $ingreso without the number at the end.

What I think its happening is that the $cont is being added at the end of the $ingreso content, not to the variable itself

Thanks for any help

</div>
  • 写回答

1条回答 默认 最新

  • duanmei1894 2016-11-16 21:51
    关注

    You should be able to do it using the complex string syntax ({}).

    while ( $cont<= 15){           
        $sql = "INSERT INTO ingreso (vlr_ingreso, periodo_ingreso, proyecto_id_proyecto)
              VALUES ('${'ingreso'.$cont}','$cont','$proyecto_id');";
        $insert = mysqli_query($con, $sql);
    }
    

    This way, the ${'ingreso'.$cont} will be parsed within the string to $ingreso1, $ingreso2, etc.

    (Also, as AbraCadaver commented, you'll also need to increment $cont for this to work.)


    This would be easier if you could make changes earlier in your code so that these were array keys rather than separate variables. For example, if you had an array like:

    $ingreso[1] = 'something';
    $ingreso[2] = 'something else';
    $ingreso[3] = 'etc.';
    

    Then you could use a foreach loop instead:

    foreach ($ingreso as $periodo => $vlr) {
        $sql = "INSERT INTO ingreso (vlr_ingreso, periodo_ingreso, proyecto_id_proyecto)
                VALUES ('$vlr','$periodo','$proyecto_id');";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?