I got an html table, and I use some loop to get some data, this data is displaying this way:
Data
... next loop
Using the modulo (%) operator is always a great solution for the problem you have above. Since you didn't provide details about the implementation language, I've taken the liberty to provide you with a php example of how it's done.
<?php
$breakPoint = 3; // This will close the <tr> tag after 3 outputs of the <td></td> tags
$data = "Data"; // Placeholder of the data
echo "<tr>";
for($i = 1; $i <= 10; $i++)
{
echo "<td>{$data}</td>";
if ($i % 3 == 0)
echo "</tr><tr>"; // Close and reopen the <tr> tag
}
echo "</tr>";
?>
If you have some counter in your loop you can use Modulus for this.
It's basically what's left of a number if you divide it.
Example:
for($i = 1; $i < 11; $i++) {
if ($i % 2 === 0) {
print('this is printed every two times');
}
if ($i % 3 === 0) {
print('this is printed every three times');
}
}
If you use a foreach()
in stead you should just make a counter yourself (as Link stated you could also use the key
of an array if it contains nice incremental keys):
$i = 1;
foreach($array as $item) {
if ($i % 2 === 0) {
print('this is printed every two times');
}
if ($i % 3 === 0) {
print('this is printed every three times');
}
$i++;
}
Or in your specific case it would look something like:
print('<tr>');
$i = 1;
foreach($array as $item) {
if ($i % 3 === 0) {
print("</tr>\n<tr>");
}
print("<td>$item</td>\n");
$i++;
}
print('</tr>');
The above is just a basic example.
You should also check whether the number of the columns is balanced and if not either add a colspan or an empty columns to balance it.