You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP foreach循环中,每6个内容的div后添加含5个内容的div?

解决交替生成6个/5个内容的Row需求

嘿,我明白你想要实现的效果——每展示完一个包含6个内容的row之后,就接着展示一个包含5个内容的row,循环这个模式直到所有内容都输出。你的现有代码已经有了基础的分组逻辑,但需要调整成交替的分组大小,我给你两种可行的方案:

方案一:分块处理(更直观)

这种方式直接把数组按6、5、6、5的规则切分,然后逐块生成row,逻辑清晰,不容易出错:

<?php $terms = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]; ?>
<div class="container text-center">
    <?php
    $totalTerms = count($terms);
    $currentIndex = 0;
    
    while ($currentIndex < $totalTerms) {
        // 先处理6个元素的row
        $sixItems = array_slice($terms, $currentIndex, 6);
        ?>
        <div class="row">
            <?php foreach ($sixItems as $term) : ?>
                <div class="col-sm-2">
                    <?php echo $term; ?>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
        $currentIndex += 6;
        if ($currentIndex >= $totalTerms) break; // 所有元素处理完就退出
        
        // 再处理5个元素的row
        $fiveItems = array_slice($terms, $currentIndex, 5);
        ?>
        <div class="row">
            <?php foreach ($fiveItems as $term) : ?>
                <div class="col-sm-2">
                    <?php echo $term; ?>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
        $currentIndex += 5;
    }
    ?>
</div>

方案二:单循环内判断分组大小

如果你更倾向于在单个foreach里处理,可以通过跟踪当前分组的目标大小来实现:

<?php $terms = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]; ?>
<div class="container text-center">
    <?php
    $count = 0;
    $currentGroupSize = 6; // 初始分组大小为6
    ?>
    <div class="row">
        <?php foreach($terms as $term) : ?>
            <?php if ($count === $currentGroupSize) : ?>
                </div>
                <?php
                // 切换分组大小:6→5,5→6
                $currentGroupSize = $currentGroupSize === 6 ? 5 : 6;
                ?>
                <div class="row">
                <?php $count = 0; ?>
            <?php endif; ?>
            
            <div class="col-sm-2">
                <?php echo $term; ?>
            </div>
            <?php $count++; ?>
        <?php endforeach; ?>
    </div>
</div>

说明

  • 方案一的优势是逻辑拆分明确,当需要调整分组规则时(比如改成7+4),修改起来非常方便,也更容易排查问题。
  • 方案二更贴近你原本的代码结构,不需要额外的循环,适合喜欢精简代码的场景。

两种方案都能完美处理你提供的22个元素(6+5+6+5刚好分完),如果后续元素数量变化,也能自动处理剩余的不足一组的元素。

内容的提问来源于stack exchange,提问作者Hiei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:12:29