2011-04-10 37 views
0

我想用foreach-call調用4行的表。PHP foreach的多行?

我的問題是,在結果中我得到每個ID在同一列20次。

我使用這個代碼:

<table width="80%" border="0" cellpadding="10px"> 

    <?php foreach (array_chunk($items, 4) as $row) { ?> 

     <?php  
     $i = 0;  
      foreach ($items as $item):  
      $class = null;  
      if ($i++ % 2 == 0) {    
      $class = ' class="altrow"';   
     } ?> 

    <tr 
     <?php echo $class;?> 
    > 

    <?php foreach ($row as $item){ ?>   
    <td> 
     <?php echo htmlentities ($item['Item']['id']); ?> 
    </td> 
    <?php } ?> 
<?php endforeach; ?>  
</tr> 
<?php } ?> 
</table> 

任何想法,我怎麼能拿每個ID只有一次?

+0

正如順便說一句,這是一個極大的方便,更易於維護使用jQuery做HTML行顏色條紋比用PHP做服務器端。 – mikel 2011-04-10 15:11:49

+0

mikel - 不一定是因爲是的,jQuery確實有它的功能,但它暗示在瀏覽器中啓用了JavaScript,並且希望讓用戶加載jQuery庫來實現可以在服務器端實現的功能。 – judda 2011-04-10 15:14:11

+1

個人喜好,我猜。不過,jQuery的方式就是「$(」。stripeMe tr:even「)。addClass(」altrow「);」 - 比我上面的PHP容易得多。儘管如此,這是無關緊要的,我不應該提到它真的... ... – mikel 2011-04-10 15:19:48

回答

2

您incrememnting $i在每一個$item而不是每一個$row

這是你正在尋找的解決?

編輯:(!一般我注意到,第一ECK)米克爾有你的修復,添加此修復行錯誤

<table width="80%" border="0" cellpadding="10px"> 
<?php 
    $i = 0; 
    $chunkedarray = array_chunk($items, 4); 
    foreach ($chunkedarray as $row) {  
     $class = null;  
     if ($i++ % 2 == 0)   
      $class = ' class="altrow"'; 
     echo "<tr ".$class.">"; 
     foreach ($row as $item){ 
      echo "<td>"; 
      echo htmlentities ($item['Item']['id']); 
      echo "</td>"; 
     } 
    echo "</tr>"; 
    }?> 
</table> 
+0

非常感謝您和@Mikel – grosseskino 2011-04-10 15:43:43