Table, TR each 2 loop, PHP, HTML

前端 未结 2 1816
挽巷
挽巷 2021-01-15 13:27

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

Data
... next loop


        
相关标签:
2条回答
  • 2021-01-15 13:36

    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>";
    ?>
    
    0 讨论(0)
  • 2021-01-15 13:48

    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.

    0 讨论(0)
提交回复
热议问题