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

如何用PHP实现可自定义行元素数的Dynamic Bootstrap Grid动态网格

动态Bootstrap网格实现代码

核心逻辑

  • 满行状态下每列宽度固定为 12 / 每行最大展示元素数
  • 最后一行元素不足时,剩余元素平分12栅格宽度计算列宽
  • 兼容处理最后一行元素不满时的row容器闭合问题

修正后PHP代码

$html = '';
$totalItemPerLine = 2; // 可自定义每行最多放的元素数
$totalItem = 3; // 可自定义总元素数
$fullColWidth = 12 / $totalItemPerLine; // 满行时单个列的宽度
$lastLineItemCount = $totalItem % $totalItemPerLine; // 最后一行的元素数量
// 计算最后一行的列宽,刚好整除的话直接用满行宽度
$lastLineColWidth = $lastLineItemCount ? 12 / $lastLineItemCount : $fullColWidth;

for($i = 0; $i < $totalItem; $i++){
    // 每到行首开启新的row容器
    if($i % $totalItemPerLine == 0){
        $html .= '<div class="row">';
    }
    
    // 判断当前元素是否在最后一行,匹配对应列宽
    $isLastLine = $i >= ($totalItem - $lastLineItemCount);
    $currentColWidth = $isLastLine ? $lastLineColWidth : $fullColWidth;
    $html .= '<div class="col-'.$currentColWidth.'"> col '.$i.'</div>';
    
    // 行满或者遍历到最后一个元素时,闭合row容器
    if($i % $totalItemPerLine == ($totalItemPerLine - 1) || $i == $totalItem - 1){
        $html .= '</div>';
    }
}

echo $html;

效果验证

修改$totalItemPerLine和$totalItem参数即可完全匹配示例规则:

  • 当$totalItem=3、$totalItemPerLine=2:输出结构对应 row col-6 col-6 row col-12
  • 当$totalItem=3、$totalItemPerLine=3:输出结构对应 row col-4 col-4 col-4
  • 当$totalItem=3、$totalItemPerLine=1:输出结构对应 row col-12 row col-12 row col-12
  • 当$totalItem=5、$totalItemPerLine=3:输出结构对应 row col-4 col-4 col-4 row col-6 col-6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:45:06