Mesut Bla
Mesut Bla

Reputation: 127

php list and group data

I want to group the data as 3 or 2 in the foreach loop while listing the data with PHP. Is it possible to do this?

There are 30 tables in total. I want to group by 3 by 3 and I want to give "first" class to the first data per group.

Like the picture I want to list. enter image description here Sample:

<div class="container">
    <?php foreach ($query as $row): ?>
        <div class="row">
            <div class="post-1 first"></div>
            <div class="post-2"></div>
            <div class="post-3"></div>
        </div>
    <?php endforeach; ?>
</div>

Upvotes: 0

Views: 210

Answers (1)

Kaan Demir
Kaan Demir

Reputation: 472

First, you pass the data you want to group into array_chunk() and determine the limit, and then we say $key==0 in the first element of each group.

<div class="container">
    <?php foreach (array_chunk($query, 3) as $chunk): ?>
        <div class="row">
            <?php foreach ($chunk as $key => $row): ?>
                <div class="post <?php if ($key == 0): ?>first<?php endif; ?>"></div>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>
</div>

Upvotes: 1

Related Questions