html-PHP:如何确定循环的第N次迭代?
我想在每3个帖子之后通过XML回显图像,这是我的代码:
// 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 '
image file
';
// 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
kwek-kwek asked 2020-01-13T12:37:05Z
8个解决方案
139 votes
最简单的方法是使用模数除法运算符。
if ($counter % 3 == 0) {
echo 'image file';
}
工作原理:模数除法返回余数。 当您为偶数倍时,余数始终等于0。
有一个陷阱:0 % 3等于0。如果您的计数器从0开始,则可能会导致意外结果。
Powerlord answered 2020-01-13T12:37:33Z
11 votes
从@Powerlord的答案开始,
“有一个陷阱:0%3等于0。这可能导致 如果您的计数器从0开始,则会出现意外结果。”
您仍然可以将计数器从0(数组,查询)开始,但是将其偏移
if (($counter + 1) % 3 == 0) {
echo 'image file';
}
Hatrix answered 2020-01-13T12:38:01Z
9 votes
使用PHP手册中的模算术运算。
例如
$x = 3;
for($i=0; $i<10; $i++)
{
if($i % $x == 0)
{
// display image
}
}
有关模数计算的更多详细信息,请单击此处。
Greg B answered 2020-01-13T12:38:30Z
5 votes
每3个帖子?
if($counter % 3 == 0){
echo IMAGE;
}
mateusza answered 2020-01-13T12:38:50Z
2 votes
怎么样:if(($ counter%$ display)== 0)
Ivar answered 2020-01-13T12:39:10Z
2 votes
我正在使用此状态更新来每1000次迭代显示一个“ +”字符,它似乎运行良好。
if ($ucounter % 1000 == 0) { echo '+'; }
meme answered 2020-01-13T12:39:30Z
1 votes
您也可以不使用模数。 只需在计数器匹配时重置计数器即可。
if($counter == 2) { // matches every 3 iterations
echo 'image-file';
$counter = 0;
}
Julez answered 2020-01-13T12:39:50Z
0 votes
它将不适合第一个位置,因此更好的解决方案是:
if ($counter != 0 && $counter % 3 == 0) {
echo 'image file';
}
自己检查。 我已经测试过为每个第4个元素添加类。
Mohan answered 2020-01-13T12:40:15Z