Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Laravel中按特定字段分组?_Laravel - Fatal编程技术网

如何在Laravel中按特定字段分组?

如何在Laravel中按特定字段分组?,laravel,Laravel,这是书桌 { "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 } { "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 } { "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 } { "_id" : 7000, "

这是书桌

{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 
}
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
我将使用Laravel雄辩的ORM得到这个结果

{ "author" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "author" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" 
] }
我该怎么办?
请帮助我。

如果
$books
收藏的实例,请尝试此代码

$collection = collect([
    [
        "title" => "The Banquet",
        "author" => "Dante",
        "copies" => 2
    ],
    [
        "title" => "Divine Comedy",
        "author" => "Dante",
        "copies" => 1
    ],
    [
        "title" => "The Odyssey",
        "author" => "Homer",
        "copies" => 10
    ]
]);

$result = [];

foreach($collection->groupBy('author') as $author => $books) {
    $data['author'] = $author;
    $data['books'] = $books->pluck('title')->all();
    $result[] = $data;
}
dd(json_encode($result));
结果是

[{"author":"Dante","books":["The Banquet","Divine Comedy"]},{"author":"Homer","books":["The Odyssey"]}]
感谢
@xyingsoft
收集数据:)没问题@davit