PHP:如何确定循环的每第N次迭代?

66

我想通过 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.
}
?>

这里是一个示例,前三个正确,但现在它不再循环:idgc.ca/web-design-samples-testing.php


建议您将问题更改为更具描述性的内容,例如“在每个第N次循环上显示图像”。 - Greg B
8个回答

169

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

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

原理是这样的: 模数运算返回余数,当你处于偶数倍时余数总是等于0。

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


3
取模运算是一种适当的方法,但如果需要执行数百万次迭代,取模操作会成为性能瓶颈,因为取模涉及到除法运算。在这种情况下,最好使用第二个计数器,将其与目标数字进行比较,并在比较匹配时重置它。 - bhelm

15

参考@Powerlord的答案,

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

您仍然可以从0开始计数(数组、查询),但需要进行偏移。

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

10
使用在PHP手册中找到的模数运算操作这里
例如。
$x = 3;

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

点击这里以更详细地了解模数计算。

5
每3篇文章?
if($counter % 3 == 0){
    echo IMAGE;
}

3
你也可以不使用模数运算。当计数器达到相应值时,只需将其重置即可。
if($counter == 2) { // matches every 3 iterations
   echo 'image-file';
   $counter = 0; 
}

2

对于第一个位置它不起作用,更好的解决方案是:

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

你自己检查一下。我已经测试过每4个元素添加类的功能。


2
如何这样写:如果(($counter % $display) == 0)

2

我正在使用这个状态更新来在每1000次迭代时显示一个“+”字符,看起来效果很好。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接