Reputation: 127
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.
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
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