Tony Tony - 2 months ago 20
HTML Question

How to generate a foreach grid table

I have this code that I am trying to make into a grid table. What I have so far generates the results all in one column. How can I make it so that when the first column reaches 10 rows a new column is created?

<table>
<thead>
<tr>
<th>Players</th>
</tr>
</thead>
<tbody>
<?php if( ( $Players = $Query->GetPlayers( ) ) !== false ): ?>
<?php foreach( $Players as $Player ): ?>
<tr>
<td align=center><?php echo "<img src=https://crafatar.com/avatars/".$Player."/?helm&size=32>
<p align=center>".$Player."</p>"; ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td>No players Online.</td>
</tr>
<?php endif; ?>
</tbody>
</table>

Answer

In the case you mentioned, you would need to gather all of the data before printing the table, build an array and do some mathematics. This is due to how the Table and it's children are Modeled. I would recommend switching to columns first, then rows if possible - like it was mentioned in the comments.

In the recommended case, it would be as follows:

$i = 1;
// start first row
echo "<tr>";

foreach($Players as $Player){

    echo "<td>" . $Player . "</td>";

    // do we need a new row?
    if($i % MAX_COLUMN_NUMBER === 0){
        echo "</tr><tr>";
    }

    // increase counter
    $i++;

}

// end final row
echo "</tr>";

If you replace MAX_COLUMN_NUMBER with 3 and have, for example, 10 items in the $Players variable, it would look like this:

╔════╤═══╤═══╗
║ 1  │ 2 │ 3 ║
╠════╪═══╪═══╣
║ 4  │ 5 │ 6 ║
╟────┼───┼───╢
║ 7  │ 8 │ 9 ║
╟────┼───┼───╢
║ 10 │   │   ║
╚════╧═══╧═══╝
Comments