我有一个包含大约90个项目的PHP对象。我试图用交替的列输出这些行。我目前的代码是每行输出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; ?>
如何修改此代码以交替每行的列数,以便输出如下:
<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>
由于
答案 0 :(得分:1)
我将我的数组块分成两块,然后按住下一个需要的键来输出不同的标记:
$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>";
答案 1 :(得分:0)
你的意思是这样的,使用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; ?>