8

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1169875
  • 141
  • 1
  • 3
  • 9
  • You could use the modulus operator `%` by simply creating an increment variable `$i=0` prior to the loop and incrementing it `++$i` in each iteration of the while loop. –  Jan 25 '12 at 19:01

3 Answers3

15

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++
}
Nanne
  • 64,065
  • 16
  • 119
  • 163
13

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>
2

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>
Brian Garson
  • 1,160
  • 6
  • 11