PHP循环在表中

时间:2017-05-24 07:09:23

标签: php

我在我的表中尝试创建循环,有4个项目,当列为3时,然后创建新行。目前的输出是这样的:

x
x
x
x

这是我的代码:

<table border="0">
      <?php
        $i = 0;
        foreach ($list_items as $item){ // there is 4 item
        $i++;
        echo "<tr>";
        if ($i <= 3) { ?>
            <td class="text-center"  style="width:83.14px; height:60.47px; font-size:0.6em">
              <?php echo $item['productId'] ?>
              <br>
              <br>
              <?php echo $item['qty'] ?>
            </td>
        <?php }
      }
      echo "</tr>";
      ?>
  </table>

我的期望是这样的:

x|x|x
x

谢谢。

4 个答案:

答案 0 :(得分:2)

在你的问题的评论部分,Sirko是对的。

无论如何,你可以像下面这样做;

<?php
    $i = 0;
    foreach ($list_items as $item) {
        if($i % 3 == 0)
            echo '<tr>';

        echo '<td> bla bla bla </td>';

        if($i % 3 == 0)
            echo '</tr>';

        $i++;
    }

答案 1 :(得分:1)

将您的代码更改为以下代码,它应该有效。

    <table border="0">
        <?php
        $i = 0;
        foreach ($list_items as $item){ // there is 4 item
            $i++;
            echo "<tr>";
            if($i%3==0) echo echo "</tr><tr>";
            ?>
                <td class="text-center"  style="width:83.14px; height:60.47px; font-size:0.6em">
                  <?php echo $item['productId'] ?>
                </td>
<td>
                  <?php echo $item['qty'] ?>
                </td>
            <?php
          }
          if($i%3!=0)
          echo "</tr>";
          ?>
      </table>

答案 2 :(得分:0)

使用array_chunk()

<?php

foreach (array_chunk($list_items,3) as $items) {
    echo '<tr>';        

    foreach($items as $item){
?>
        <td class="text-center"  style="width:83.14px; height:60.47px; font-size:0.6em">
          <?php echo $item['productId'] ?>
          <br>
          <br>
          <?php echo $item['qty'] ?>
        </td>
<?php
    }
    echo '</tr>';
}
?>

答案 3 :(得分:0)

试试这个==&gt;

    <table border="0">
        <?php
        $i = 0;
        foreach ($list_items as $item) { // there is 4 item
            if ($i % 3 == 0)  // for i=0,3,6,9 <tr> tag will open
                echo "<tr>";

            ?>
            <td class="text-center"  style="width:83.14px; height:60.47px; font-size:0.6em">
                <?php echo $item['productId'] ?>
                <br>
                <br>
                <?php echo $item['qty'] ?>
            </td>
            <?php
            if ($i % 3 == 0)  // for i=0,3,6,9 <tr> tag will close
                echo "</tr>";

$i++;
        }
        ?>
    </table>