mysql查询结果分成组

时间:2011-05-23 19:31:48

标签: php mysql

从mysql查询中,我希望将5个结果作为一个组包装成li。如何?感谢

$counter = 1;
while($row = mysql_fetch_array($result)){
echo '<li>';
if ( ($counter % 5) == 0 ){           
echo '<div class="title">'.$row['title'].'</div>';
}
$counter ++;
echo '</li>';
}
}

我想要一些html输出,比如

<li><div class="title">something</div><div class="title">something</div><div class="title">something</div><div class="title">something</div><div class="title">something</div></li>
<li><div class="title">something</div><div class="title">something</div><div class="title">something</div><div class="title">something</div><div class="title">something</div></li>
<li><div class="title">something</div><div class="title">something</div><div class="title">something</div><div class="title">something</div><div class="title">something</div></li>
... <!-- 5 results in one li -->

3 个答案:

答案 0 :(得分:3)

您需要让你的mod%关闭li或打开li,而不是处理div

这样的事情:

$counter = 1;
while($row = mysql_fetch_array($result)) {
    if ( $counter % 5 == 1 ) {           
        echo '<li>';
    }
    echo '<div class="title">'.$row['title'].'</div>';
    if ( $counter % 5 == 0 ) {           
        echo '</li>';
    }
    $counter ++;
}
if ( $counter % 5 != 1 ) {           
    echo '</li>';
}

没有测试过,但它应该有助于让你走上正确的道路。

答案 1 :(得分:2)

你似乎很亲密,怎么样:

$counter = 0;
while($row = mysql_fetch_array($result)){
        if (($counter % 5) == 0) {
            echo '<li>';
        }
        echo '<div class="title">'.$row['title'].'</div>';
        if (($counter % 5) == 4) {
            echo '</li>';
        }
        $counter ++;
    }
}
if ($counter % 5 != 4) {           
    echo '</li>';
}

答案 2 :(得分:1)

$x = mysqli_num_rows($result);   
$counter = 0;

while($row = mysql_fetch_array($result)){
if ( ($counter % 5) == 0 ){
echo '<li>'
}           
echo '<div class="title">'.$row['title'].'</div>';
if (((($counter +1) % 5) == 0) || (($counter+1)==$x)){
echo '</li>'
} 
$counter ++;
}

我没有检查它,但mysqli_num_rows变量可用于最后关闭。