我想要每个div 3个项目(样本总共有7个项目),如下所示:
<div>
<item/>
<item/>
<item/>
</div>
<div>
<item/>
<item/>
</div>
但我做不到
while($r = mysql_fetch_array($q){
?><item/><?
}
if(++$i%3==1){
//blabla:)
}
因为它打印错误
<div>
<item/>
<item/>
<item/>
</div>
<div>
<item/>
...
如何以3块为单位正确打印出项目?
答案 0 :(得分:2)
你大部分都在那里。
$result = mysql_query("SELECT ....");
$recordCounter = 0;
$record = mysql_fetch_assoc($result);
while ($record) {
if ($recordCounter % 3 == 0) {
?>
<div class="item-block">
<?php
}
?>
<div class="item"></div>
<?php
$record = mysql_fetch_assoc($result);
$recordCounter++;
if ($record === false || $recordCounter % 3 == 0) {
?>
</div>
<?php
}
}
mysql_free_result($result);
答案 1 :(得分:2)
稍微缩短:))
<div class="items">
<? $q = mysql_query("SELECT * FROM table ");
$i=1;
while($r = mysql_fetch_array($q))
{
?><item /><?
if($i%4==0){?></div><div class="item"><? }?>
<? $i++;
}?>
</div>
答案 2 :(得分:1)
这是另一种选择,也许有太多的php标签=)
<?php
$items = array(1,2,3,4,5,6,7,8);
$count = 1;
?>
<html>
<body>
<?php foreach ($items as $item) : ?>
<?php if ($count == 1) : ?>
<div>
<?php endif; ?>
<p><?php echo $item; ?></p>
<?php if ($count == 3) : ?>
</div>
<?php $count = 0; ?>
<?php endif; ?>
<?php $count++; ?>
<?php endforeach; ?>
</body>
</html>