2017-05-24 99 views
0

我想创建循环在我的表中,有4个项目,当列是3,然后创建新的行。电流输出是这样的:PHP循环在表

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 

谢谢。

+1

您需要将您的'tr'环路内。 – Albzi

+3

我建议使用'flex'布局而不是'table'布局。那个换行符只是CSS规则。 – Sirko

回答

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>'; 
} 
?> 
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

更改您的代码下面,它应该工作。

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

有关您更改内容的一些说明以及为什么? –

+0

查看if条件,如果项目达到3,它将打印close tr并开始新的tr。 –

0

试试这个==>

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