Abs
Abs

Reputation: 57996

Dynamic Table Layout using PHP Logic

I have simple table that has about 80 rows, which I populate dynamically using PHP. What I am trying to do is to layout those rows in chunks for each column. So if I have 80 rows, I would like 4 columns of 20 rows or so, maybe the last column has less or more depending on the total number of rows. The total number of rows can change!

I am having trouble coming up with an implementation method that will not get messy! Anyone know of a simple way that I can implement this.

I have tried using a counter as I loop the data to populate the table and when a multiple of of 20 is reached move to the next block but that didn't work for me as I had extra rows left over.

foreach($indexes as $index){

    $counter++;

    echo '<tr>';

    if($counter > 20){

        $multiplier = $counter / 20;

        $head = '<td></td>';

        for($i=1; $i<$multiplier; $i++){

            $head .= '<td></td>';

        }

    }

    if($counter < 20){

        $head = ''; 

    }

    echo "$head<td>$index</td><td><input id='$index' name='$index' type='checkbox' /></td>";  

    echo '</tr>';

}

Thanks all for any help

Upvotes: 0

Views: 881

Answers (3)

Toto
Toto

Reputation: 91518

I would do :

$nbCols = 4;
$nbRows = count($indexes)/$nbCols;
for($row=0; $row<$nbRows; $row++) {
    echo "<tr>";
    for($i=0; $i<$nbCols; $i++) {
        $index = $indexes[$row + ($i*$nbRows)];
        echo "<td>$index</td><td><input id='$index' name='$index' type='checkbox' /></td>";
    }
    echo "</tr>";
}

Upvotes: 1

Adam Lukaszczyk
Adam Lukaszczyk

Reputation: 4926

if you dont mind to have this kind of cell order:

1 2 3 4
5 6 7 8

you can use <div style='float:left'>$cellValue</div> in the loop without use of table.

Upvotes: 0

David Yell
David Yell

Reputation: 11855

Wouldn't you want to see the remainder of your division and deal with that also?

if($counter % 20 == 0){
  // You've no remainder
}else{
  // Do another loop to output the odd rows
}

Or you could % 2 == 0 to see if it's even, and then just multiply the whole result by 10.

Be sure to look at ceil() and floor() also for ensuring your number of rows is a round number.

Upvotes: 0

Related Questions