2009-06-01 80 views
40

我想以後通過XML這裏3員額回聲圖像的每個是我的代碼:PHP:你如何確定循環的每一次第N次迭代?

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

+1

請使用StackOverflow代碼格式化模式。您的代碼現在不可讀。 – 2009-06-01 19:10:37

+0

問題是什麼? 還可以看看在文本區中可用的格式化工具.. – 2009-06-01 19:11:01

回答

123

最簡單的方法是使用模數除法運算符。

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

這是如何工作的: 模量除法返回餘數。當你處於偶數倍時,餘數總是等於0。

這裏有一個陷阱:0 % 3等於0。這可能會導致意想不到的結果,如果你的計數器從0開始

8

在PHP手冊中使用找到的模運算操作here

例如

$x = 3; 

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

想要更詳細地瞭解模量計算,請點擊here

2

怎麼樣的:if(($計數器%$顯示)== 0)

5

每3個帖子?

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

我正在使用此狀態更新來每1000次迭代顯示一個「+」字符,它似乎工作正常。

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

都會響起的@ Powerlord的回答,

「這裏有一個陷阱:0%3等於0。這可能會導致 意外的結果,如果你的計數器從0開始。」

你仍然可以開始你在0(數組,querys)計數器,但偏向它

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

你也可以不用模量。當它匹配時重置你的櫃檯。

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