[英]Group by on nested laravel collection
I have started working on some data analyising, and the data is really messy, so i have to convert timestamps to readable date and time and such..我已经开始研究一些数据分析,数据真的很乱,所以我必须将时间戳转换为可读的日期和时间等等。
I have tried standard group by but it was not successful because the array is nested and i have no idea how to approach.我尝试过标准组,但没有成功,因为数组是嵌套的,我不知道如何处理。
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => Array
(
[name] => Entity 1
[values] => Array
(
[0] => Array
(
[date] => 08.07.2019
[time] => 00:00
[counter] => 1
)
[1] => Array
(
[date] => 08.07.2019
[time] => 01:00
[counter] => 3
)
[167] => Array
(
[date] => 14.07.2019
[time] => 23:00
[counter] => 0
)
)
)
[1] => Array
(
[name] => Entity 2
[values] => Array
(
[0] => Array
(
[date] => 08.07.2019
[time] => 00:00
[counter] => 0
)
[1] => Array
(
[date] => 08.07.2019
[time] => 01:00
[counter] => 4
)
[2] => Array
(
[date] => 08.07.2019
[time] => 02:00
[counter] => 12
)
[3] => Array
(
[date] => 09.07.2019
[time] => 03:00
[counter] => 0
)
[4] => Array
(
[date] => 10.07.2019
[time] => 04:00
[counter] => 4
)
[5] => Array
(
[date] => 11.07.2019
[time] => 05:00
[counter] => 17
)
)
)
So what would be the correct way to group this by date so i could get one array for one date for example那么按日期分组的正确方法是什么,以便我可以为一个日期获取一个数组,例如
date 08.07: time: 02:00 counter: 12日期 08.07:时间:02:00 计数器:12
timer: 04:00
counter: 1
date 14.07: time: 05:00 counter: 1日期 14.07:时间:05:00 计数器:1
time: 08:00
counter: 3
time: 01:00
counter: 6
Sorry for dump example of an array对不起,转储数组的例子
I have tried something like:我尝试过类似的事情:
$collection = collect($values);
$groupedBy = $collection->groupBy('date);
But that just doesn't work since it's a nested array.但这不起作用,因为它是一个嵌套数组。
Before grouping you could reduce the collection in order to have only the items' values.在分组之前,您可以减少集合以便只有项目的值。 After that you can simply use group by date and time:
之后,您可以简单地按日期和时间使用分组:
$grouped = $collection
->reduce(function(Collection $carry, $item) {
return $carry->merge($item['values']);
}, new Collection())
->groupBy(function($item) {
return sprintf('%s %s', $item['date'], $item['time']);
});
where Collection
is the imported Illuminate\\Support\\Collection
其中
Collection
是导入的Illuminate\\Support\\Collection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.