php Laravel 集合上的多个 groupBy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30468966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple groupBy on Laravel Collection
提问by Michalis Antoniou
I am trying to group a collection by two clauses in Laravel 5, but it only groups it by the first one. Can someone please help me out? Here's my code.
我试图在 Laravel 5 中按两个子句对集合进行分组,但它只按第一个子句分组。有人可以帮我吗?这是我的代码。
$query = Activity::all()->groupBy('performed_at_year_month', 'performer_id')->toJson();
回答by Erik
The solution in https://stackoverflow.com/a/30469061/221745can be improved on I think. The key is to remember that a grouped by collection is a collection of collections. Therefore, the following will work:
我认为可以改进https://stackoverflow.com/a/30469061/221745 中的解决方案。关键是要记住,按集合分组是集合的集合。因此,以下将起作用:
<?php
$recs = new \Illuminate\Database\Eloquent\Collection($query);
$grouped = $recs->groupBy('performed_at_year_month')->transform(function($item, $k) {
return $item->groupBy('performer_id');
});
Where $grouped
contains your final result
哪里$grouped
包含你的最终结果
回答by user1669496
You can try chaining them, however I am not sure it will get you the results you want. May want to check to be sure
您可以尝试链接它们,但是我不确定它会为您带来想要的结果。可能需要检查以确保
$query = Activity::all()->groupBy('performed_at_year_month')->groupBy('performer_id')->toJson();
I just checked this and you are correct, it's not preserving keys, although I think I can guess why. If a key happens to be the same, things will get overwritten. It could also be difficult to determine which key is what and overall feels a little "hacky" where there is likely a much better solution.
我刚刚检查了这个,你是对的,它没有保留密钥,虽然我想我能猜到原因。如果密钥恰好相同,则内容将被覆盖。也可能很难确定哪个键是什么,并且总体感觉有点“hacky”,其中可能有更好的解决方案。
However, I think I've figured out how to do this.
但是,我想我已经想出了如何做到这一点。
$query = Activity::all();
$activities = new \Illuminate\Database\Eloquent\Collection($query);
$activities = $activities->groupBy('performed_at_year_month')->toArray() + $activities->groupBy('performer_id')->toArray();
echo json_encode($activities);
回答by Bedram Tamang
Instead of passing a string key, you may pass a callback. The callback should return the value you wish to key the group by:
您可以传递回调而不是传递字符串键。回调应返回您希望通过以下方式键入组的值:
$collection->groupBy(function($item, $key){
return $item["key-1"]."-".$item["key-2"];
});
Reference:- https://laravel.com/docs/5.7/collections#method-groupby
参考:- https://laravel.com/docs/5.7/collections#method-groupby