PHP:你如何确定每个循环的第N次迭代? [英] PHP: How do you determine every Nth iteration of a loop?
问题描述
I wanted to echo an image every after 3 post via XML here is my code :
$ b // XML提要的URL。
$ feed ='test.xml';
//我们要显示多少项?
// $显示= 3;
//检查我们的XML文件是否存在
if(!file_exists($ feed)){
die('The XML file could not be found!');
}
//首先,打开XML文件。
$ xml = simplexml_load_file($ feed);
//设置计数器来统计我们显示的项目数量。
$ counter = 0;
//启动循环显示每个项目。
foreach($ xml->后期为$ post){
echo'
< div style =float:left; width:180px; margin-top:20px; margin-bottom :10px的;>
图片档案< / a> < div class =design-sample-txt>'。 $后>作者< / DIV>< / DIV>
';
//增加一个计数器。
$ counter ++;
//选中以显示我们想要的所有项目。
if($ counter> = 3){
echo'image file';
}
// if($ counter == $ display){
//是的。结束循环。
// break;
//}
//号码继续。
}
?>
<?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
推荐答案
最简单的方法是使用模数除法运算符。 b
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.
有一个catch: 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屋!