php - 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']。怎么做?
解决方案
尝试这个:
$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);
});
});
推荐阅读
- javascript - 使用 JavaScript 将鼠标悬停在元素上?
- amazon-cognito - AWS-Cognito 和 Shibboleth 有什么区别?
- apache-kafka - Pub/Sub 和消费者感知发布。没有人订阅时停止生产
- android - 为什么在行生成器中未使用 setPrimaryAction 时切片未在 sliceviewer apk 中呈现
- javascript - 转换 tfjs 模型以在 C++ 中的 Tensorflow 中使用
- javascript - 当节点频繁更新时,清理事件侦听器或任何其他附加资源
- node.js - 从流响应中读取并将其写入另一个响应节点 js
- python - 如何将此函数转换为生成器?
- css - Firefox 和 Chrome 中的 Flexbox 换行和溢出行为不同
- python-3.x - Matplotlib 颜色错误