【问题标题】:Run script every 1st and 4th time inside a PHP while loop based on MySQL result根据 MySQL 结果在 PHP while 循环中每 1 次和 4 次运行一次脚本
【发布时间】:2014-10-19 07:42:21
【问题描述】:

我有一个 while loop 从 MySQL 表中获取数据。返回的行数未知。我想在loop 中的每个第 1 项和第 4 项中运行部分代码,例如:

while ($result = $stmt->fetch()) {

   //Run on first row always, then repeat on the 4th item and so on.
   echo '<div class="row">';

}

我该怎么做?

【问题讨论】:

  • 简单的 if/else 带有存储循环迭代的标志变量
  • @MKhalidJunaid 你能详细说明一下吗?

标签: php mysql loops while-loop


【解决方案1】:
// keep track of the iteration count
$i = 1;

while ($result = $stmt->fetch()) {

    //if it's the first iteration, open the row
    if($i == 1) { echo '<div class="row">'; }

    //...

    // NOTE: count($results) is pseudocode, make sure you provide it somehow
    // if you're on the 4nth or the last iteration 
    if($i % 4 == 0 or $i == count($results))
    {
        // close the row
        echo '</div>';

        // if it's not the last item in the loop, open a new row
        if($i != count($results)) { echo '<div class="row">'; }
    }

    $i++;
}

【讨论】:

  • $results 来自哪里?
  • 正如评论所说,这是伪代码。我不知道结果来自哪里或如何计算它们。我现在说得更清楚了。
  • 谢谢!正是我需要的。
猜你喜欢
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 2011-11-02
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
相关资源
最近更新 更多