【问题标题】:Generating table for database records为数据库记录生成表
【发布时间】:2012-01-21 07:08:44
【问题描述】:

以下代码将在每个$product->title 上生成<tr></tr>

<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>

【问题讨论】:

  • 可以让一个php程序重复数到3吗?
  • 是的,应该加在3个之后
  • 好的,那你知道怎么初始化一个变量,加一个,测试看看是不是3了吗?如果是,你知道如何导致“
  • ”生成吗?如果你这样做了,你就完成了。

标签: php html database html-table


【解决方案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>

【讨论】:

  • @"因为没有正确回答问题而投反对票(product->$value 来自哪里?)"。它来自一个产品类。我将数据库的每个字段都添加为类的属性。当类中的方法从数据库中获取记录并将每个值分配给属性时,它就会成为对象的对象。抱歉,我不太了解投票或否决我是新来的。我只是点击了这没有帮助:P
【解决方案2】:

大概是这样的:

<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 变量使用计数器。

【讨论】:

    【解决方案3】:
        $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>
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签