Reputation: 13
There is such a loop, I want to get 4 repetitions of the div with the class tabs__cat-img and these 4 div should turn into a div with the class tabs_ _ cat. I will be grateful for any help.
<?php
if($children_categories) :
foreach($children_categories as $children_cat) :
?>
<div class="tabs__cat">
<div class="tabs__cat-img">
<a href="">
<img src="" alt="">
</a>
</div>
</div>
<?php
endforeach;
endif;
?>
The output should look like this:
<div class="tabs__cat">
<div class="tabs__cat-img">
<a href="">
<img src="" alt="">
</a>
</div>
<div class="tabs__cat-img">
<a href="">
<img src="" alt="">
</a>
</div>
<div class="tabs__cat-img">
<a href="">
<img src="" alt="">
</a>
</div>
<div class="tabs__cat-img">
<a href="">
<img src="" alt="">
</a>
</div>
</div>
<div class="tabs__cat"> ...
Upvotes: 1
Views: 63
Reputation: 798
You just need to change your code a little bit.
I moved the parent div which has class tabs__cat
from the foreach
loop.
<?php
$children_categories = array_fill(0, 4, 'Sample');
if($children_categories) :
echo '<div class="tabs__cat">'; // small changed here
foreach($children_categories as $children_cat) :
?>
<div class="tabs__cat-img">
<a href="">
<img src="" alt="">
</a>
</div>
<?php
endforeach;
echo '</div>'; // small changed here
endif;
?>
Upvotes: 0
Reputation: 1391
I would do it like this:
<?php
// Creates a sample array
$children_categories = array_fill(0, 10, 'Sample');
if($children_categories) :
$total_categories = count($children_categories) - 1;
foreach($children_categories as $id=>$children_cat) :
// True for 0 -> Div will be created on first and then every 4th element
if( $id % 4 === 0 ) {
echo '<div class="tabs__cat">';
}
// or, a bit shorter:
// echo $id % 4 === 0 ? '<div class="tabs__cat">' : '';
?>
<div class="tabs__cat-img">
<a href="">
<img src="" alt="">
</a>
</div>
<?php
// True on 3 -> closing Div will be created before 4th and then every 4th element
// Or Case: Make sure to print closing div on very last element
if( $id % 4 === 3 || $id === $total_categories ) {
echo '</div>';
}
endforeach;
endif;
?>
Upvotes: 1