Laravel groupBy 返回项目数组而不是使用日期作为键
Posted
技术标签:
【中文标题】Laravel groupBy 返回项目数组而不是使用日期作为键【英文标题】:Laravel groupBy return array of items instead of using date for key 【发布时间】:2021-06-03 07:13:21 【问题描述】:我正在使用 Laravel groupBy
方法来格式化我的数据并将它们分组到句点中,但是,我想更改返回结果的方式。而不是使用created_at
作为数组项的键,我不希望有一个键,而是将那个键移到返回的结果中......
以下代码将返回:
"results": [
"2021-03-04":
"event_category": "category",
"event_action": "action",
"event_count": "544",
"period_from": "2021-03-04 00:00:00",
"period_to": "2021-03-04 10:30:02",
"created_at": "2021-03-04 10:30:06"
,
"2021-03-03":
"event_category": "category",
"event_action": "action",
"event_count": "5337",
"period_from": "2021-03-03 00:00:00",
"period_to": "2021-03-03 23:57:03",
"created_at": "2021-03-03 23:57:08"
]
看起来是这样的
$res = DB::table('my_table')
->select('event_category', 'event_action', 'event_count', 'period_from', 'period_to', 'created_at')
->where([["event_category", "category"], ["event_action", "action"], ["period_from", ">=", "2021-03-01"], ["period_to", "<=", "2021-03-04 22:00:00"]])
->orderBy('created_at, 'desc')
->get();
$results = $res->groupBy(function ($item, $key) use ($findable)
$date = Carbon::parse($item->created_at);
return $date->format($findable['groupByFormat']);
);
$results = $results->map(function ($item, $key)
return $item[0];
);
$res = $results;
我想回来...
"results": [
[
"event_category": "category",
"event_action": "action",
"event_count": "544",
"period_from": "2021-03-04 00:00:00",
"period_to": "2021-03-04 10:30:02",
"created_at": "2021-03-04 10:30:06",
"new_created_at": '2021-03-04'
],
[
"event_category": "category",
"event_action": "action",
"event_count": "5337",
"period_from": "2021-03-03 00:00:00",
"period_to": "2021-03-03 23:57:03",
"created_at": "2021-03-03 23:57:08",
"new_created_at": '2021-03-03'
]
]
我尝试删除我的初始地图,但不确定如何在保留分组的同时实现这种格式
【问题讨论】:
你试过 Flatten 方法了吗? 【参考方案1】:尝试以下方法:
$results = $results->map(function ($items, $key)
return array_merge($items, ['new_created_at' => $key]);
)->values();
最后对 values() 的调用只返回集合的值,以便它以数字而不是日期作为键。
Illuminate\Support\Collection #337 ▼
#items: array:2 [▼
0 => array:7 [▼
"event_category" => "category"
"event_action" => "action"
"event_count" => "544"
"period_from" => "2021-03-04 00:00:00"
"period_to" => "2021-03-04 10:30:02"
"created_at" => "2021-03-04 10:30:06"
"new_created_at" => "2021-03-04"
]
1 => array:7 [▶]
]
【讨论】:
以上是关于Laravel groupBy 返回项目数组而不是使用日期作为键的主要内容,如果未能解决你的问题,请参考以下文章
Laravel VueJS - 输入值数组返回字符串而不是数组
如何使用 Laravel response()->json() 返回空对象而不是空数组
使用 phpunit DB::table()->get() 测试 Laravel 4.2 返回数组而不是对象