Laravel blade 模板的 @foreach 循环中,对集合使用 groupBy 函数的方法
admin 阅读:20 2024-03-02
Laravel 框架中集合的groupBy
方法可以根据指定键对集合项进行分组:
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->all();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
那么,我们如果在后台的时候不方便对集合进行groupBy
操作,也可以在模板中调用groupBy
:
@foreach($collection->groupBy('account_id) as $account_id => $group)
{{ $account_id }}
@foreach($group as $value)
{{ $value->product }}
@endforeach
@endforeach
声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!