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

kwe*_*wek 52 html php loops

我希望通过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.
}
?>
Run Code Online (Sandbox Code Playgroud)

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

Pow*_*ord 140

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

if ($counter % 3 == 0) {
   echo 'image file';
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

小智 11

离开@Powerlord的回答,

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

你仍然可以在0(阵列,查询)开始你的计数器,但抵消它

if (($counter + 1) % 3 == 0) {
  echo 'image file';
}
Run Code Online (Sandbox Code Playgroud)


Gre*_*g B 9

使用中发现模运算这里 PHP手册.

例如

$x = 3;

for($i=0; $i<10; $i++)
{
    if($i % $x == 0)
    {
        // display image
    }
}
Run Code Online (Sandbox Code Playgroud)

有关模数计算的更详细信息,请单击此处.


mat*_*sza 5

每3个帖子?

if($counter % 3 == 0){
    echo IMAGE;
}
Run Code Online (Sandbox Code Playgroud)