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

如何根据结果数量将div拆分为两列或三列(PHP foreach输出场景)

问题排查

现有代码的错误点:

  • 多写了一个</div>闭合标签,提前结束了row容器
  • 没有为每个表单项添加col-md-6的外层列容器,无法实现两列等分效果
  • 缺少奇数个元素场景下的row闭合逻辑,易出现标签嵌套错误

修正后代码

$j = 0;
$itemCount = count($data['properties']);
foreach($data['properties'] as $value){            
    if ($j % 2 == 0) {
        $this->html .= '<div class="row">';
    } 
    // 新增半宽列容器
    $this->html .= '<div class="col-md-6">';
    $this->html .= '<div class="form-group '.$style.'">';
    $this->html .= $this->parse($value);
    $this->html .= '</div>';
    $this->html .= '</div>';
    // 每满2个元素或者遍历到最后一个元素时闭合row
    if ($j % 2 == 1 || $j == $itemCount - 1) {
        $this->html .= '</div>';
    }
    $j++;
}

效果验证

上述代码输出的DOM结构完全符合你提供的预期HTML格式,不管遍历的表单项总数是奇数还是偶数,都能保证标签正常闭合,自适应两列布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:15:03