如何在laravel中使用json键名分组结果


user table 
id name age 
1  TuTu   3
2  SuSu   4
3  YuYu   4
4  MoMo   4

我想这样输出json。

[
{
"age": 3,
"user": [
{
"id": 2,
"name": "TuTu"
}
]
},
{
"age": 4,
"user": [
{
"id": 2,
"name": "SuSu"
},
{
"id": 3,
"name": "YuYu"
},
{
"id": 4,
"name": "MoMo"
}
]
}
]

User::get()->groupBy("age")不能正常工作

如何在laravel中添加json键年龄和用户像上面的格式?

答案给出了您想要的输出,但是请考虑为JSON响应使用API资源。

$response = [];
User::get()->groupBy('age')->each(function ($item, $key) use (&$response) {
$temp = [];
$temp['age'] = $key;
$temp['user'] = $item->transform(function ($i, $k) {
unset($i['age']);
return $i;
})->all();
$response[] = $temp;
});
var_dump($response); // Your Output JSON

最新更新