Insert tr after every third loop

不问归期 提交于 2019-12-17 20:21:31

问题


I'm making a forum in PHP. I have to display all forum categories in a table, and to do so, I have used a while loop. However, I want to have only 3 td's in every table row. To loop through the categories, I'm using a while loop with the query, so I don't think I can use modulus here.


回答1:


Why can't you use modulus? Just add a counter somewhere, and if it hits % 3 == 0 reset the counter and do your stuff.

You might need to do some extra if's for first and last and stuff like that, but there is no reason not to use a modulo with a while.

$i=0;
while(guard()){
    if($i % 3 == 0){
       //ploing
    }
 $i++
}



回答2:


This code will close any extra rows:

<table>
<?php
$columns = 3;
$i = 0;
while($row = mysql_fetch_array($result)){
    $i++;
    //if this is first value in row, create new row
    if ($i % $columns == 1) {
        echo "<tr>";
    }
    echo "<td>".$row[0]."</td>";
    //if this is last value in row, end row
    if ($i % $columns == 0) {
        echo "</tr>";
    }
}
//if the counter is not divisible by the number of columns, we have an open row
$spacercells = $columns - ($i % $columns);
if ($spacercells < $columns) {
    for ($j=1; $j<=$spacercells; $j++) {
        echo "<td></td>";
    }
    echo "</tr>";
}
?>
</table>



回答3:


I haven't tested the code, but the logic should work:

<Table>
<?php
$i = 0;
while($row = mysql_fetch_array($result)){
    if($i == 0){
        echo"<TR>";
    }
    echo"<td>".$row[0]."<TD>";
    $i++;
    if($i == 3)
    {
        $i = 0;
        echo"</tr>"
    }
}
if($i ==1){
    echo "<td></td><td></td></tr>";
}
if($i ==2)
{
    echo "<td></td></tr>";
}
?>
<table>


来源:https://stackoverflow.com/questions/9008522/insert-tr-after-every-third-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!