在 Laravel 中,如果同一用户数组有多个响应,我想更改响应
我通过此功能得到了回复
控制器.php
public function index(){
$reports = Report::all();
return $this->sendResponse($reports->toArray(), 'User Reports successfully.');
}
这是我的回应
{
"success": true,
"data": [
{
"id": 66,
"cuid": 20,
"name": "my1",
"created_at": "2018-03-09 00:00:00",
"updated_at": "2018-03-09 00:00:00",
"time": "07:19 PM",
"status": "D"
},
{
"id": 65,
"cuid": 20,
"name": "my1",
"created_at": "2018-03-07 00:00:00",
"updated_at": "2018-03-07 00:00:00",
"time": "07:39 PM",
"status": "D"
},
{
"id": 64,
"cuid": 21,
"name": "my2",
"created_at": "2018-03-02 00:00:00",
"updated_at": "2018-03-05 00:00:00",
"time": "07:01 PM",
"status": "D"
},
{
"id": 63,
"cuid": 20,
"name": "my2",
"created_at": "2018-03-02 00:00:00",
"updated_at": "2018-03-02 00:00:00",
"time": "06:44 PM",
"status": "D"
}
],
"message": "User Reportsssss successfully."
}
这很好,我的问题是我有 4 个数组,其中有 2 个用户插入显示,我想这样显示
{
"success": true,
"data": [
my1:{
{
"id": 66,
"cuid": 20,
"name": "my1",
"created_at": "2018-03-09 00:00:00",
"updated_at": "2018-03-09 00:00:00",
"time": "07:19 PM",
"status": "D"
}
{
"id": 65,
"cuid": 20,
"name": "my1",
"created_at": "2018-03-07 00:00:00",
"updated_at": "2018-03-07 00:00:00",
"time": "07:39 PM",
"status": "D"
}
},
my2:{
{
"id": 63,
"cuid": 21,
"name": "my2",
"created_at": "2018-03-07 00:00:00",
"updated_at": "2018-03-07 00:00:00",
"time": "07:39 PM",
"status": "D"
}
{
"id": 64,
"cuid": 21,
"name": "my2",
"created_at": "2018-03-02 00:00:00",
"updated_at": "2018-03-05 00:00:00",
"time": "07:01 PM",
"status": "D"
}
}
],
"message": "User Reportsssss successfully."
}
如果同一用户位于单个数组下,如何实现此目的
执行此操作的理想方法是使用收集管道。你原来的控制器方法将变成以下;
public function index(){
$reports = Report::all();
return $this->sendResponse($reports->groupBy('name')->toArray(), 'User Reports successfully.');
}
groupBy
方法会将集合结果拆分为其他集合,并按提供的列进行分组。因为 toArray()
方法会级联,所以你会得到一个不错的数组。
您需要循环遍历结果并根据您的要求进行修改。我已经测试了以下代码,其工作正常。尝试使用它。
$reports = $reports->toArray();
$finalArray = [];
foreach($reports as $key=>$value) {
$name = $value['name'];
$finalArray[$name][] = $value;
}
return $this->sendResponse($finalArray, 'User Reports successfully.');
谢谢。