生成数据库记录表

时间:2012-01-21 07:08:45

标签: php html database html-table

以下代码将在每<tr></tr>

生成$product->title
<table>
    <?php foreach ($products as $product) {
            echo '<tr>
                      <td>'.$product->title.'</td>
                  </tr>';
    }?>
</table>

但我想在每三列之后生成一行作为上述代码的输出。

<table>
    <tr>
            <td>$product->title/td>
            <td>$product->title/td>
            <td>$product->title</td>
    </tr>
            <td>$product->title</td>
            <td>$product->title</td>
            <td>$product->title</td>
    </tr>
</table>

3 个答案:

答案 0 :(得分:1)

我非常喜欢这种形式,它致力于输入内存。

<table>
<?php
    $count = 0;  // we gotta count them lines
    foreach ($products as $product)
    {
        if ( ($count % 3) == 0 )  // every 3 lines
        {
            if ($count > 0)  // not at first line
                echo '</tr>';  // close previous row
            echo '<tr>';  // open new row
         }
         ++$count;  // better count this one now.

         echo '<td>'.$product->title.'</td>;
    }
    if ($count > 0) 
        echo '</tr>';  // close last row
?>
</table>

答案 1 :(得分:0)

    $i=1;
    <table>
        <?php foreach ($products as $product) {
           if ( $i<= 3 ) {
               if($i==1) {
                 echo '<tr>';
               }    
               echo '<td>'.$product->title.'</td>';
               $i++;
           }
           else {
               echo'</tr>';
               $i=1;
           }
        }?>
    </table>

答案 2 :(得分:0)

也许是这样的:

<table>
<?php
   $count = count($products); 
   foreach ($products as $key => $product) {
        // print on first row and third row
        if($key % 3 == 0) {
            echo '<tr>';
        }
        echo '<td>'.$product->title.'</td>';
        // print on third row or on last element
        if((($key + 1) % 3 == 0 && $key > 0) || $key == $count-1) {
            echo '</tr>';
        }
   }
?>
</table>

如果数组未从0开始编制索引,则必须使用$key变量的计数器。