Yii2使用foreach生成3列表

时间:2018-11-01 09:25:33

标签: foreach yii2

如何使用以下代码在页面中仅生成3列     如果我在里面保留echo'(table)'会生成整个表,所以我只想要一张表     在3列追加新行

后,页面中仅允许3列
     <?php
        $i = 0;
        echo  '<table style="float: left;width: -weekbit-fill-available"; ><tr>';
        ?>
        <?php foreach ($product as $p) {
            $i++;



           // $i++;
            echo "<tr><td>Name:<b>". $p->name ."</td></tr>";
            echo "<tr><td>productID:<b>".$p->proid ."</td></tr>";
            echo "<tr><td>Price:<b>". $p->price ."</td></tr>";
            echo "<tr><td><a href='/cart/cart/add?id=$p->proid'><input type='button' value='addtocart'/></td></tr>";


            if($i==3){
                echo '</tr><tr>';
            }

            echo"</tr>
                        </table>";
            ?>
        <?php }?>
        <?php  echo"</tr>
                        </table>"?>

thanks in advance

2 个答案:

答案 0 :(得分:1)

尝试以下

<table style="float: left; width: -weekbit-fill-available">
<tr>
    <th>Name</th>
    <th>ProductID</th>
    <th>Price</th>
    <th>Action</th>
</tr>
<?php foreach ($product as $p) : ?>
    <tr>
        <td><?= $p->name ?></td>
        <td><?= $p->proid ?></td>
        <td><?= $p->price ?></td>
        <td colspan="3"><?= \yii\helpers\Html::a('addtocart',
        ['/cart/cart/add', 'id' => $p->proid],
        [
            'title' => 'Add to Cart',
            'class' => 'btn btn-warning btn-sm',
        ]); ?></td>
    </tr>
<?php endforeach; ?>
</table>

答案 1 :(得分:0)

对每一行使用<tr>,对每一列使用<td>

    <table style="float: left; width: -weekbit-fill-available"; >
        <?php foreach ($product as $p): ?>
        <tr>
            <td>Name: <b><?= $p->name ?></td>
            <td>productID: <b><?=  $p->proid ?></td>
            <td>Price: <b><?= $p->price ?></td>
            <td><a href='/cart/cart/add?id=<?= $p->proid ?>'><input type='button' value='addtocart'/></td>
        </tr>
        <?php endforeach; ?>
    </table>";

另请参阅: