【问题标题】:How can iterate every 5 results in a table?如何迭代表中的每 5 个结果?
【发布时间】:2016-11-10 08:15:46
【问题描述】:

我有一个 foreach,需要在表上每行每 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 个数据。它可能会变得或多或少

注意:

如果可能,为空的每一列的宽度都应为 20%

【问题讨论】:

标签: php codeigniter loops foreach


【解决方案1】:

解决问题的简单方法:

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

【讨论】:

  • 最后添加
  • 嗯.. 我的 foreach 应该返回 24 个结果。但代码只打印 20 个结果。
  • @Vahn 你能print_r($klasifikasi)
  • 我刚刚修复了其中一个 if 语句,现在可以了
  • @krasipenkov 非常感谢。只是一个小问题。如何在“png”行之后添加一个空行(用于空格目的)?
【解决方案2】:

使用嵌套循环。外部循环应该迭代 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>";
}

【讨论】:

  • 谢谢。但是,我必须使用 foreach。不是为了。我正在使用 CodeIgniter
  • 我从未使用过 CodeIgniter。为什么它强迫你使用foreach
猜你喜欢
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 2020-02-09
  • 2018-06-11
  • 2018-11-21
  • 1970-01-01
相关资源
最近更新 更多