0

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

3 Answers 3

1

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>";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.