这是Book表
{ "_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 Eloquent ORM得到这个结果。
{ "author" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "author" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues"
] }我该怎么做呢?请帮帮我。
发布于 2018-12-20 03:14:54
如果$books是Collection的实例,请尝试此代码
$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提供的采集数据
https://stackoverflow.com/questions/53857712
复制相似问题