<?php $list = [ [ 'create_at' => '2023-01-02', 'currency_type' => 'ONE', 'settlement' => 3 ], [ 'create_at' => '2023-01-27', 'currency_type' => 'ONE', 'settlement' => 5 ], [ 'create_at' => '2023-01-02', 'currency_type' => 'TWO', 'settlement' => 4 ], [ 'create_at' => '2023-03-02', 'currency_type' => 'ONE', 'settlement' => 7 ], [ 'create_at' => '2023-05-02', 'currency_type' => 'ONE', 'settlement' => 6 ], ]; $new_list = [ 'ONE' => [ [ 'time' => '2022-12', 'settlement' => 0 ], [ 'time' => '2023-01', 'settlement' => 8 ], [ 'time' => '2023-02', 'settlement' => 7 ], [ 'time' => '2023-03', 'settlement' => 0 ], [ 'time' => '2023-04', 'settlement' => 0 ], [ 'time' => '2023-05', 'settlement' => 6 ], ], 'TWO' => [ [ 'time' => '2022-12', 'settlement' => 0 ], [ 'time' => '2023-01', 'settlement' => 4 ], [ 'time' => '2023-02', 'settlement' => 0 ], [ 'time' => '2023-03', 'settlement' => 0 ], [ 'time' => '2023-04', 'settlement' => 0 ], [ 'time' => '2023-05', 'settlement' => 0 ] ], ]; 如何将$list变成$new_list?规则是按currency_type分组,同一月份settlement求和,time为最近半年时间
时间: 2024-01-16 09:04:38 浏览: 60
可以按照以下步骤将$list变成$new_list:
1. 定义一个空数组$grouped_list用来存储按currency_type分组后的数据。
2. 遍历$list数组,将每个元素按currency_type分组存储到$grouped_list数组中。
3. 遍历$grouped_list数组,对于每个currency_type,按照时间顺序生成半年内的时间段,初始化一个空数组$monthly_data用来存储该时间段内的数据,并将其存储到$new_list数组中对应currency_type的位置。
4. 遍历$grouped_list数组中每个currency_type的数据,将数据按照时间分组到$monthly_data数组对应的时间段中,并对每个时间段内的settlement求和,更新$monthly_data数组。
5. 将$monthly_data数组中的数据存储到$new_list数组中对应currency_type的位置。
下面是代码实现:
```php
$new_list = [];
$grouped_list = [];
// 按currency_type分组
foreach ($list as $item) {
$currency_type = $item['currency_type'];
if (!isset($grouped_list[$currency_type])) {
$grouped_list[$currency_type] = [];
}
$grouped_list[$currency_type][] = $item;
}
// 处理每个currency_type
foreach ($grouped_list as $currency_type => $data) {
// 初始化时间段数据
$six_months_ago = strtotime('-6 months');
$monthly_data = [];
for ($i = 0; $i < 6; $i++) {
$time = date('Y-m', strtotime("+$i months", $six_months_ago));
$monthly_data[$time] = [
'time' => $time,
'settlement' => 0,
];
}
// 按时间分组,求和
foreach ($data as $item) {
$time = date('Y-m', strtotime($item['create_at']));
if (isset($monthly_data[$time])) {
$monthly_data[$time]['settlement'] += $item['settlement'];
}
}
// 存储到$new_list中
$new_list[$currency_type] = array_values($monthly_data);
}
```
阅读全文