是否可以从laravel分组/重新排列JSON输出?我想在它发送到系统查看之前对它进行分组,所以我需要在服务器端而不是客户端完成它。
让我说我的JSON结构如下:
id, name, date
或者在示例中,是这样的:
[[
{"id" : "1", "name" : "A", "date" : "2017-01-01"},
{"id" : "2", "name" : "B", "date" : "2017-01-01"},
{"id" : "3", "name" : "C", "date" : "2017-01-01"},
{"id" : "4", "name" : "D", "date" : "2018-01-01"},
{"id" : "5", "name" : "E", "date" : "2018-01-01"},
]]
是否可以将它分组为这样的东西?
[
{"2017-01-01":[
{"id":"1","name":"A"},
{"id":"2","name":"B"},
{"id":"3","name":"C"}
]},
{"2018-01-01":[
{"id":"4","name":"D"},
{"id":"5","name":"E"},
]},
]
(如果你需要查看我的JSON控制器)这是我的JSON控制器:
public function harga($id)
{
$harga = harga::whereHas('produk', function ($query) use($id) {
$query->where('id',$id);
})->get();
return response()->json([$harga],200);
}
谢谢!
答案 0 :(得分:3)
在您的查询中使用groupBy:
public function harga($id)
{
$harga = harga::whereHas('produk', function ($query) use($id) {
$query->where('id',$id);
})->get()->groupBy(column_name_you_want_to_group_by);
return response()->json([$harga],200);
}
答案 1 :(得分:2)
您可以使用groupBy
方法执行此操作:
return response()->json($harga->groupBy('date'), 200);
答案 2 :(得分:0)
在控制器中可以执行以下操作
js = "your json";
$jsArray = json_decode($js, true);
$jsArray = $jsArray[0];
$newJsArr = [];
foreach ($jsArray as $j) {
$newJsArr[$j['date']][] = ["id" => $j['id'], "name" => $j['name']];
}
$newJsArr = json_encode([$newJsArr]);