【发布时间】:2020-05-22 12:27:23
【问题描述】:
您好,我有预订和开始时间。现在我需要报告它。
$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']。怎么办?
【问题讨论】:
-
使用
return [$arrkey[1]=>$item]; -
@AnantSingh---AlivetoDie nope 然后我有
array:2 [▼ "01" => array:1 [▼ 0 => 60 ] "02" => array:1 [▼ 0 => 420 ] ]