Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert tr after every third loop

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.

like image 759
user1169875 Avatar asked Jan 25 '12 18:01

user1169875


2 Answers

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++
}
like image 124
Nanne Avatar answered Sep 23 '22 19:09

Nanne


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>
like image 20
Nicholas Kouvatsos Avatar answered Sep 22 '22 19:09

Nicholas Kouvatsos