PHP:您如何确定循环的每第 N 次迭代? [英] PHP: How do you determine every Nth iteration of a loop?

查看:18
本文介绍了PHP:您如何确定循环的每第 N 次迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanted to echo an image every after 3 post via XML here is my code :

<?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

here is a sample first 3 are correct but now it doesn't loop idgc.ca/web-design-samples-testing.php

推荐答案

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

The easiest way is to use the modulus division operator.

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

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

How this works: Modulus division returns the remainder. The remainder is always equal to 0 when you are at an even multiple.

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

There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0.

这篇关于PHP:您如何确定循环的每第 N 次迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆