Table, TR each 2 loop, PHP, HTML

2020-03-26 20:37发布

I got an html table, and I use some loop to get some data, this data is displaying this way:

<tr><td>Data</td></tr>
... next loop

But I wan't it to close table row (tr) every 2 or even 3 loops. So the data may look like this:

<tr>
<td>Data</td>
<td>Data1</td>
<td>Data2</td>
</tr>

...next loop...

Will you help me with this?

2条回答
在下西门庆
2楼-- · 2020-03-26 21:13

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>";
?>
查看更多
神经病院院长
3楼-- · 2020-03-26 21:21

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.

查看更多
登录 后发表回答