我想每隔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-design-samples-testing.php
最简单的方法是使用模数除法运算符。
if ($counter % 3 == 0) { echo 'image file'; }
工作原理:模数除法返回余数。当您为偶数倍时,余数始终等于0。
有一个陷阱:0 % 3等于0。如果您的计数器从0开始,可能会导致意外结果。
0 % 3