2016-11-10 87 views
0

我有一個foreach需要在表上每5行結果分發一次。如何在表中迭代每5個結果?

這是我目前的foreach:

<?php 

    $i = 0; 
    echo "<tr>"; 

    foreach($klasifikasi as $result){ 
     $i++; 


     if($i % 5 == 0){ 
     echo "<td width='20%' align='center'>".$result['klasifikasi']."</td>"; 
     echo "<td width='20%' align='center'>".$result['klasifikasi']."png</td>"; } 

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

它不會停止每隔5的結果,並且不產生新行。

這就是我在尋找:

--------------------------------------------------- 
A1  | A2  | A3  | A4  | A5 
--------------------------------------------------- 
A1.png | A2.png | A3.png | A4.png | A5.png 
--------------------------------------------------- 
/*this row should be empty for some spacing*/ 
--------------------------------------------------- 
.../*skipped till the last row*/ 
--------------------------------------------------- 
A21  | A22  |  A23  | A24 
--------------------------------------------------- 
A21.png | A22.png |  A23.png | A24.png 
--------------------------------------------------- 

我從當前迭代的結果是24個數據。它可能會變得或多或少

注:

如果可能的話,每列是空應該有widht 20%

+0

看一看這個帖子從昨天 - http://stackoverflow.com/questions/40510272/php-how-to-sort-output 4055043#40510543 – Blinkydamo

+0

您並未在您的'foreach'loop中創建行,您正在創建單元格。 – simon

+0

是否有任何'foreach'解決方案?不是'for' – Vahn

回答

0

一個簡單的解決問題的方法:

$i = 1; 
    $html = "<table border='1'>"; 

    $row1 = '<tr>'; 
    $row2 = '<tr>'; 
    foreach($klasifikasi as $result){ 
     $row1 .= "<td width='20%' align='center'>".$result['klasifikasi']."</td>"; 
     $row2 .= "<td width='20%' align='center'>".$result['klasifikasi']."png</td>"; 

     if($i > 0 && $i % 5 === 0){ 
      $row1 .= '</tr>'; 
      $row2 .= '</tr>'; 
      $html .= $row1.$row2; 
      $html .= '<tr><td colspan="5"></td></tr>; 

      $row1 = '<tr>'; 
      $row2 = '<tr>'; 
     } 
     $i++; 
    } 

    if($i > 0 && $i % 5 !== 1) { 
     $html .= $row1.$row2; 
    } 
    $html .= '</table>'; 
    echo $html; 
+0

什麼都不打印。回聲在哪裏? – Vahn

+0

添加到底 – krasipenkov

+0

嗯..我的foreach應該返回24個結果。但代碼只打印20個結果。 – Vahn

0

使用嵌套循環。外循環應迭代5,內循環獲取該組內的5個項目。

$len = count($klasifikasi); 
for ($i = 0; $i < $len; $i += 5) { 
    echo "<tr>"; 
    for ($j = $i; $j < $i+5; $j++) { 
     if ($j < $len) { 
      echo "<td>{$row['klasifikasi']}</td>"; 
     } 
    } 
    echo "</tr>"; 
    echo "<tr>"; 
    for ($j = $i; $j < $i+5; $j++) { 
     if ($j < $len) { 
      echo "<td>{$row['klasifikasi']}.png</td>"; 
     } 
    } 
    echo "</tr>"; 
} 
+0

謝謝。但是,我必須使用foreach。不是爲了。我使用CodeIgniter – Vahn

+0

我從來沒有使用過CodeIgniter。爲什麼它強迫你使用'foreach'? – Barmar