I have a PHP object with around 90 items. I am trying to output these in rows with alternating columns. My current code is outputting 2 items per row is:
<?php
$_collectionSize = $_productCollection->count();
$_columnCount = 2;
$i = 0;
?>
<?php foreach ($_productCollection as $_product): ?>
<?php if ($i++ % $_columnCount == 0): ?>
<section class="row">
<?php endif ?>
<div class="six columns"></div>
<?php if ($i % $_columnCount == 0 || $i == $_collectionSize): ?>
</section>
<?php endif ?>
<?php endforeach; ?>
How can I modify this code to alternate the column count for each row so that the output would be like:
<div class="row">
<div class="six columns"></div>
<div class="six columns"></div>
</div>
<div class="row">
<div class="three columns"></div>
<div class="three columns"></div>
<div class="three columns"></div>
<div class="three columns"></div>
</div>
<div class="row">
<div class="six columns"></div>
<div class="six columns"></div>
</div>
<div class="row">
<div class="three columns"></div>
<div class="three columns"></div>
<div class="three columns"></div>
<div class="three columns"></div>
</div>
Thanks
I would chunk my array in chunks by two, and then hold next needed key for outputting different markup:
$items = array(
'Product 1',
'Product 2',
'Product 3',
'Product 4',
'Product 5',
'Product 6',
'Product 7',
'Product 8',
'Product 9',
'Product 10',
'Product 11',
'Product 12',
);
$chunked = array_chunk($items, 2);
// variable to hold next <div class="six columns"></div> markup
$needle = 0;
foreach ($chunked as $key => $items) {
if ($key == $needle) {
if ($key !== 0) echo "</div>\n";
echo "<div class=\"row\">\n";
foreach($items as $item) {
echo "<div class=\"six columns\">{$item}</div>\n";
}
echo "</div>\n<div class=\"row\">\n";
// skip two array items
$needle = $needle + 3;
} else {
foreach($items as $item) {
echo "<div class=\"three columns\">{$item}</div>\n";
}
}
}
echo "</div>";
You mean something like that, using a modulo of 2 ? :
<?php foreach ($_productCollection as $_product): ?>
<?php if ($i++ % $_columnCount == 0): ?>
<section class="row">
<?php endif ?>
<?php if ($i % 2 == 0): ?>
<div class="six columns"></div>
<div class="six columns"></div>
<?php else ?>
<div class="three columns"></div>
<div class="three columns"></div>
<div class="three columns"></div>
<div class="three columns"></div>
<?php endif ?>
<?php if ($i % $_columnCount == 0 || $i == $_collectionSize): ?>
</section>
<?php endif ?>
<?php endforeach; ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.