首页 > 解决方案 > Laravel 通过更改键分组

问题描述

嗨,我有预订和他们的开始时间。现在我需要报告它。

        $monthlyAmounts = Reservation::all()
        ->groupBy(function ($proj) {
            return cdate($proj->start_time)->format('Y-m');
        })
        ->map(function ($month) {
            return $this->sumTime($month);
        });

sumTime 是我计算开始时间和结束时间之间差异的函数。cdate 是助手-> carbon::parse($date)..

结果是:

array:2 [▼
  "2020-01" => 60
  "2020-02" => 420
]

需要

但对于 API,最好是这样:

[
    "2020" => [
        '01' => 60,
        '02' => 30
    ],
    "2021" => [
        '01' => 30,
    ]
]

我的尝试

不幸的是我不能那样做。我试过了:

    $monthlyAmounts = Reservation::all()
        ->groupBy(function ($proj) {
            return cdate($proj->start_time)->format('Y-m');
        })
        ->map(function ($month) {
            return $this->sumTime($month);
        })
        ->mapToGroups(function ($item,$key) {
            $arrkey = explode('-',$key);
            return [$arrkey[0]=>[$arrkey[1]=>$item]];
        });

但它使这个:

array:1 [▼
  2020 => array:2 [▼
    0 => array:1 [▼
      "01" => 60
    ]
    1 => array:1 [▼
      "02" => 420
    ]
  ]
]

所以我不能做 $res['2020']['01']。怎么做?

标签: phplaraveleloquent

解决方案


尝试这个:

$monthlyAmounts = Reservation::all()
        ->groupBy(function ($proj) {
            return cdate($proj->start_time)->format('Y');
        })
        ->map(function ($items) {
            return $items->groupBy(function($item) {
                return cdate($item->start_time)->format('m');
            })
            ->map(function($month) {
                return $this->sumTime($month);
            }); 
        });

推荐阅读