[英]How can I alternate the column count per row?
我有一個大約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>
謝謝
我將數組分成兩塊,然后按住下一個需要的鍵以輸出不同的標記:
$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>";
您的意思是,使用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.