分组并汇总集合

时间:2019-02-07 07:56:46

标签: laravel laravel-collection

我不知道是否有一种简单的方法可以完成我想做的事情,所以我想我也应该问一下。我确实在寻找这个问题的答案,但找不到类似的东西。

我有一个名为$data的变量,它包含一个看起来像这样的集合:

[
    "date" => "2017-10-07 10:00:00"
    "usage" => 0.423
    "costs" => 1.212
],
[
    "date" => "2017-10-07 11:00:00"
    "usage" => 0.786
    "costs" => 1.564
],
[
    "date" => "2017-10-07 12:00:00"
    "usage" => 0.542
    "costs" => 1.545
]

(数据可以长达2个月的每小时记录,出于可读性考虑,我在此示例中选择仅包含3个小时)

如您所见,全部都是每小时每小时(这也是我代码中不同部分所需的数据),我希望每天单独收集。有没有一种简单的方法可以按日期('Ymd')分组并求和usagecosts?我还应该提到并非集合中的所有项目都具有所有索引。有些没有usage,有些没有costs。所有人都有date

1 个答案:

答案 0 :(得分:2)

您可以通过以下方式实现此目标:

$collection = collect([
    [
        "date" => "2017-10-07 10:00:00",
        "usage" => 0.423,
        "costs" => 1.212
    ],
    [
        "date" => "2017-10-07 11:00:00",
        "usage" => 0.786,
        "costs" => 1.564
    ],
    [
        "date" => "2017-10-07 12:00:00",
        "usage" => 0.542,
        "costs" => 1.545
    ],
    [
        "date" => "2017-10-08 10:00:00",
        "costs" => 1.1
    ],
    [
        "date" => "2017-10-08 11:00:00",
        "usage" => 0.786,
    ],
    [
        "date" => "2017-10-08 12:00:00",
        "costs" => 1.567
    ]
]); 


return $collection->groupBy(function($row) {
    return Carbon\Carbon::parse($row['date'])->format('Y-m-d'); 
})->map(function($value, $key) {
    return [
        'usage' => $value->sum('usage'), 
        'costs' => $value->sum('costs')
    ];
});

以上内容的输出为:

Collection {#267 ▼
  #items: array:2 [▼
    "2017-10-07" => array:2 [▶]
    "2017-10-08" => array:2 [▼
      "usage" => 0.786
      "costs" => 2.667
    ]
  ]
}

从上面可以看到,某些项目没有usagecosts。它仍然可以工作。

这也是您可以玩的example