[英]How can I alternate the column count per row?
I have a PHP object with around 90 items. 我有一个大约90个项目的PHP对象。 I am trying to output these in rows with alternating columns. 我试图将这些输出以交替列的形式输出。 My current code is outputting 2 items per row is: 我当前的代码每行输出2个项目是:
<?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 ? 您的意思是,使用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; ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.