如何动态地将列表分成不同的div

how to separate lists into different divs dynamically

美好的一天,

我的页面中有一个类别列表,但可以随时添加或删除。你能帮我制定一个循环,将 divide 我的列表变成每个 div.

最多 5 个列表吗

例如

foreach($categories as $cat)
  <label><input type ="checkbox"><?php echo $cat->name ?></label></br>
endforeach

以上代码将在 1 列中生成一个复选框列表

所以我尝试了这个循环

<?php $count = 0; ?>
    @foreach($categories as $cat)
    @if($count == 0)
    <div class="col-md-4">
    @elseif($count == 5)
    <?php $count = 0; ?>
    </div>
    @endif
    <label><input type="checkbox" value="{{$cat->xid}}">{{$cat->category}}</label><br>
    <?php $count++; ?>
    @endforeach

它生成这样

但它只包装列表中的前 5 个元素,接下来的 5 个元素不起作用。你能帮我吗:)非常感谢你的建议

这是原版 PHP,但您可以轻松地使用 blade 模板中的逻辑。我测试过,效果很好。

<?php
   $categories = ['test','test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7',
'test','test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7','test','test1',
'test2', 'test3', 'test4', 'test5', 'test6', 'test7','test','test1', 'test2', 'test3',
'test4', 'test5', 'test6', 'test7'];
$end = end($categories);

$count = 1;
foreach($categories as $cat){ 
   if($count == 1 || $count % 5 == 1){
      echo '<div class="col-md-5">';
   }
?>

<label><input type ="checkbox"><?php echo $cat ?></label></br>

<?php
   if(($count % 5 == 0) && $count != 0 || ($cat == $end)){
     echo '</div>';
   }
   $count++;
} 
?>

以下是您的代码,我修改后将生成所需的布局。您需要将 CSS 应用于 class="col-md-4" 以根据您的要求分隔每个块。

<?php $count = 0; ?>
 @foreach($categories as $cat)
 @if($count == 0)
   <div class="col-md-4">
 @endif

 @if($count> 0 && $count%5 == 0)
      </div>
      <div class="col-md-4">
 @endif

 <label><input type="checkbox" value="{{$cat->xid}}">{{$cat->category}}     
 </label><br>
 <?php $count++; ?>
@endforeach

@if($count <= 5)
  </div>
@endif