我创建了2个集合(数组),每个集合包含5个项目/事件的数组。
$events = App\get_event_data( $args )
$collection = collect($events['events']);
$event_chunks = $collection->chunk(5);
$event_chunks->toArray();
@foreach ($event_chunks as $chunk)
以上内容的输出
object(Illuminate\Support\Collection)[27632]
protected 'items' =>
array (size=2)
0 =>
object(Illuminate\Support\Collection)[27630]
protected 'items' =>
array (size=5)
...
1 =>
object(Illuminate\Support\Collection)[27631]
protected 'items' =>
array (size=5)
...
在我的下一个循环中,它只是简单地遍历了数组的每一项1。
我需要将5个项目分为另外2个组:
2人一组
3人一组
所以我可以将div围绕每个组。
当前循环:
@foreach ($chunk as $key => $event)
<div class="item">
{{ $event['title'] }}
</div>
@endforeach
我需要什么:
<div class="item-group">
[item1, item2]
</div>
<div class="item-group">
[item3, item4, item5]
</div>
完整代码:
{{-- Get all events --}}
@if( $events = App\get_event_data( $args ) )
@php
$collection = collect($events['events']);
$event_chunks = $collection->chunk(5);
$event_chunks->toArray();
@endphp
@foreach ($event_chunks as $chunk)
<div class="{{ $block }}__flex-grid">
@foreach ($chunk as $key => $event)
<div class="item">
{{ $event['title'] }}
</div>
@endforeach
</div>
@endforeach
@endif
答案 0 :(得分:1)
假设您始终有5件商品,则解决方案可能是:
<div class="item-group">
@foreach (array_slice($chunk->toArray(),0,2) as $key => $event)
<div class="item">
{{ $event['title'] }}
</div>
@endforeach
</div>
<div class="item-group">
@foreach (array_slice($chunk->toArray(),2) as $key => $event)
<div class="item">
{{ $event['title'] }}
</div>
@endforeach
</div>
或者如果要避免代码重复:
@php $chunk = [array_slice($chunk->toArray(),0,2), array_slice($chunk,2)];
@foreach ($chunk as $group)
<div class="item-group">
@foreach ($group as $key => $event)
<div class="item">
{{ $event['title'] }}
</div>
@endforeach
</div>
@endforeach
如果您不确定或不确定是否有5个,则可能需要更改块/切片的逻辑。