【问题标题】:PHP: How do you determine every Nth iteration of a loop?PHP:如何确定循环的每 N 次迭代?
【发布时间】:2010-10-30 11:47:22
【问题描述】:

我想通过 XML 每隔 3 个帖子回显一个图像,这是我的代码:

<?php
// URL of the XML feed.
$feed = 'test.xml';
// How many items do we want to display?
//$display = 3;
// Check our XML file exists
if(!file_exists($feed)) {
  die('The XML file could not be found!');
}
// First, open the XML file.
$xml = simplexml_load_file($feed);
// Set the counter for counting how many items we've displayed.
$counter = 0;
// Start the loop to display each item.
foreach($xml->post as $post) {
  echo ' 
  <div style="float:left; width: 180px; margin-top:20px; margin-bottom:10px;">
 image file</a> <div class="design-sample-txt">'. $post->author.'</div></div>
';

  // Increase the counter by one.
  $counter++;
  // Check to display all the items we want to.
  if($counter >= 3) {
    echo 'image file';
    }
  //if($counter == $display) {
    // Yes. End the loop.
   // break;
  //}
  // No. Continue.
}
?>

这是一个示例,前 3 个是正确的,但现在它不会循环 idgc.ca/web-design-samples-testing.php

【问题讨论】:

  • 建议您将问题更改为更具描述性的内容,例如“每第 N 个循环显示图像”

标签: php html loops


【解决方案1】:

最简单的方法是使用模除法运算符。

if ($counter % 3 == 0) {
   echo 'image file';
}

这是如何工作的: 模除法返回余数。当你在偶数倍数时,余数总是等于0。

有一个问题:0 % 3 等于 0。如果您的计数器从 0 开始,这可能会导致意外结果。

【讨论】:

  • 模数是一种正确的方法,但如果您进行数百万次迭代,这可能会成为性能瓶颈,因为模数涉及除法。在这种情况下,您最好使用第二个计数器,将其与所需的数字进行比较,并在比较匹配时将其重置。
【解决方案2】:

离开@Powerlord 的回答,

"有一个问题:0 % 3 等于 0。这可能导致 如果您的计数器从 0 开始,则会出现意外结果。”

您仍然可以从 0 开始计数器(数组、查询),但要偏移它

if (($counter + 1) % 3 == 0) {
  echo 'image file';
}

【讨论】:

    【解决方案3】:

    使用 PHP 手册中 here 中的模数运算。

    例如

    $x = 3;
    
    for($i=0; $i<10; $i++)
    {
        if($i % $x == 0)
        {
            // display image
        }
    }
    

    如需更详细了解模数计算,请点击here

    【讨论】:

      【解决方案4】:

      每 3 个帖子?

      if($counter % 3 == 0){
          echo IMAGE;
      }
      

      【讨论】:

        【解决方案5】:

        您也可以不使用模数。只需在匹配时重置您的计数器。

        if($counter == 2) { // matches every 3 iterations
           echo 'image-file';
           $counter = 0; 
        }
        

        【讨论】:

          【解决方案6】:

          怎么样:if(($counter % $display) == 0)

          【讨论】:

            【解决方案7】:

            我正在使用此状态更新来每 1000 次迭代显示一个“+”字符,它似乎运行良好。

            if ($ucounter % 1000 == 0) { echo '+'; }
            

            【讨论】:

              【解决方案8】:

              它不适用于第一位置,因此更好的解决方案是:

              if ($counter != 0 && $counter % 3 == 0) {
                 echo 'image file';
              }
              

              请自行检查。我已经测试了它为每个第 4 个元素添加类。

              【讨论】: