如何在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