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