我想在每3篇文章后通过XML回显一个图像以下是我的代码:
<?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设计示例测试。php
最简单的方法是使用模除运算符。
if ($counter % 3 == 0) {
echo 'image file';
}
工作原理:模除法返回余数。当你处于偶数倍数时,余数总是等于0。
有一个问题:0%3
等于0。如果计数器从0开始,这可能会导致意外的结果。
偏离了@Powerlord的答案,
“有一个陷阱:0%3等于0。如果计数器从0开始,这可能会导致意想不到的结果。"
您仍然可以从0(数组、查询)开始计数器,但可以将其偏移
if (($counter + 1) % 3 == 0) {
echo 'image file';
}
使用PHP手册中的模算术操作。
例如。
$x = 3;
for($i=0; $i<10; $i++)
{
if($i % $x == 0)
{
// display image
}
}
有关模量计算的更多详细信息,请单击此处。