繁体   English   中英

如何更改每行的列数?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM