0

I have code like this

<table>
<tr>
   <th>No</th>
   <th>Title</th>
   <th>Name</th>
</tr>    
foreach($value as $item){
        echo "<tr>";
        echo "<td>".$item['no']."</td>";
        echo "<td>".$item['title]."</td>";
        echo "<td>".$item['data']."</td>";
        echo "</tr>";
}
</table>

For example I have 5 items in my loop. My loop output now something like this:

| No |   Title  |  Name |
|----|----------|-------|
| 1  |    Book  | Susan |
| 2  |   Comic  |  Budi |
| 3  |   Recipe | Anwar |
| 4  |  Magazine|  Leo  |
| 5  |   Novel  | Clara |

But I want output like this with the looping header also Image

1
  • Why would you want it this way? How is this more useful to the reader than row by row? Commented Jul 2, 2019 at 4:01

2 Answers 2

2

You may try array_chunk to split array as 3 items in each row first.

$value = [
    ['no' => '1', 'title' => 'Book', 'data' => 'Susan'],
    ['no' => '2', 'title' => 'Comic', 'data' => 'Budi'],
    ['no' => '3', 'title' => 'Recipe', 'data' => 'Anwar'],
    ['no' => '4', 'title' => 'Magazine', 'data' => 'Leo'],
    ['no' => '5', 'title' => 'Novel', 'data' => 'Clara']
];

$value = array_chunk($value, 3);

echo '<table>';
foreach ($value as $row) {
    echo '<tr>';
    foreach ($row as $item) {
        echo '<td>'.$item['no'].'</td>';
        echo '<td>'.$item['title'].'</td>';
        echo '<td>'.$item['data'].'</td>';
    }
    echo '</tr>';
}
echo '</table>';
Sign up to request clarification or add additional context in comments.

1 Comment

This was great, thank you for sharing.
0

You can modify and use modulus operator to close raw and open raw.

replace your loop data and test it.

$i = 1;
echo '<tr>';
foreach ($row as $item) {
    echo '<td>'.$item['no'].'</td>';
    echo '<td>'.$item['title'].'</td>';
    echo '<td>'.$item['data'].'</td>';
    if($i % 3 == 0) {
        echo '</tr><tr>';
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.