如何在Div循环内嵌套Foreach?实现Swiper分页展示数据库数据
实现每3条数据分组到Swiper轮播幻灯片的解决方案
完全可以在div循环内嵌套foreach,这是实现需求的直接方案。核心思路是先把数据库返回的数组按3条一组分割,再外层循环每组生成一个Swiper幻灯片,内层循环每组内的数据生成表格行。
具体实现代码
<?php // 将数据按每3条分割成二维数组 $branchGroups = array_chunk($branch, 3); ?> <!-- Swiper容器 --> <div class="swiper"> <div class="swiper-wrapper"> <?php foreach ($branchGroups as $group) : ?> <div class="swiper-slide"> <table class="table table-image"> <tbody> <?php foreach ($group as $branchs) : ?> <tr> <td class="w-25"> <img src="image/icon/<?= $branchs['imgtitle']; ?>" class="img-fluid img-thumbnail" alt="Sheep"> </td> <td> <h4> <b><?= $branchs['title']; ?></b> </h4> <p class="card-text"><?= $branchs['text']; ?></p> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> <?php endforeach; ?> </div> <div class="swiper-pagination"></div> </div>
补充说明
array_chunk($branch, 3)是PHP内置函数,会把原数组分割成多个子数组,每个子数组最多包含3个元素,最后一组如果不足3条也会保留。- 外层foreach负责生成每个
swiper-slide容器,内层foreach负责渲染当前幻灯片里的表格行,逻辑清晰易维护。
内容的提问来源于stack exchange,提问作者daun babadotan
相关产品推荐
相关产品推荐

