将结果分为5列 [英] Split results into 5 columns
问题描述
我有一个查询,例如:
$results = Post::all();
为简单起见,假设输出是这样的(通过id
):
For the sake of simplicity, let's say the output is this (by id
):
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
我的网站有5列布局.我需要将这些结果拆分/划分为5列,以使其最终像这样:
My website has a 5-column layout. I need to split/divide these results into 5 columns such that it ends up like this:
1 | 2 | 3 | 4 | 5
6 | 7 | 8 | 9 | 10
11 | 12 | 13 | 14 | 15
5列布局是这样分割的(总列数为25):
The 5 column layout is split like this (the total number of columns is 25):
<div class="row">
<div class="col-xs-5">
//
</div>
<div class="col-xs-5">
//
</div>
<div class="col-xs-5">
//
</div>
<div class="col-xs-5">
//
</div>
<div class="col-xs-5">
//
</div>
</div>
如何像这样拆分$results
?是否可以使用Laravel的收集方法?
How can I split $results
up like this? Any way to make use of Laravel's Collection methods?
推荐答案
尝试一下,我认为它应该给您预期的结果
Try this , i think it should give you the expected result
$chunks = $results->chunk(5);
dd($chunks->toarray());
Laravel文档
chunk方法将集合分成多个较小的集合 给定大小的收藏
The chunk method breaks the collection into multiple, smaller collections of a given size
它也可以像这样在视图中使用(在控制器中保留相同的查询并在视图中进行拆分)
also it can be used in the View like this ( keep the same query in the controller and do the splitting in the View)
编辑
@foreach ($results->chunk(5) as $chunk)
<div class="row">
@foreach ($chunk as $test)
<div class="col-md-2">
{{ $test->id }}
</div>
@endforeach
</div>
@endforeach
输出
这篇关于将结果分为5列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!