Vahn Vahn - 23 days ago 11
PHP Question

How can iterate every 5 results in a table?

I have a foreach that need to be distributed every 5 result per row on a table.

This is my current 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>";
?>


It doesn't stop every 5 result and doesn't create new row.

This is what I'm looking for:

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


My current result from the iteration is 24 data. It may become more or less

note:

if possible, every columns that are not empty should have widht of 20%

Answer

A simple solution to your problem:

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