【问题标题】:php how to loop append to variablephp如何循环追加到变量
【发布时间】:2018-01-19 07:00:47
【问题描述】:

我有这个有效的 PHP 代码:

for ($i=0; $i < 5; $i++) {
    do stuff to $class
    echo "<i class=\"glyphicon glyphicon-star $class\"></i>";
}

我如何在循环中不使用echo,而是将每个迭代附加到一个变量(比如$stars),然后能够显示结果

echo "$stars";

【问题讨论】:

  • echo => $stars.=
  • PHP string concatenation的可能重复
  • 也仅供参考,echo $stars;echo "$stars"; 具有相同的效果。双引号不是必需的。

标签: php


【解决方案1】:

创建一个变量来保存您的 HTML。将 HTML 连接到此变量而不是回显它。

在循环之后,您可以回显该变量。

$stars = '';
for ($i=0; $i < 5; $i++) {
    // do stuff to $class
    $stars .= "<i class=\"glyphicon glyphicon-star $class\"></i>";
}
echo $stars;

【讨论】:

    【解决方案2】:

    你可以像这样使用串联赋值.=

    $var='';
    for ($i=0; $i < 5; $i++) {
        do stuff to $class
        $var.="<i class=\"glyphicon glyphicon-star $class\"></i>";
    }
    echo $var;
    

    【讨论】:

      【解决方案3】:

      或者,您可以在不使用输出缓冲修改现有代码的情况下执行此操作。

      // start a new output buffer
      ob_start();
      
      for ($i=0; $i < 5; $i++) {
          //do stuff to $class
      
          // results of these echo statements go to the buffer instead of immediately displaying
          echo "<i class=\"glyphicon glyphicon-star $class\"></i>";
      }
      
      // get the buffer contents
      $stars = ob_get_clean();
      

      对于这样一个简单的事情,我仍然会使用与 .= 的连接,如其他答案所示,但仅供参考。

      【讨论】:

        猜你喜欢
        • 2013-09-22
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 2022-07-27
        • 1970-01-01
        • 1970-01-01
        • 2017-06-18
        • 2015-03-22
        相关资源
        最近更新 更多