You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何从给定数据集按月份聚合周数据?

解决方案

核心思路

  1. 遍历数据集中的每个指标(如val1、val2)
  2. 将年周格式的键(如202201)转换为YYYY-MM格式的年月标识
  3. 按年月分组,累加同一月份下对应指标的数值
  4. 整理为目标格式的数组

代码实现(PHP)

$dataset = [
    'val1' => ['202201' => '1', '202202' => '2', '202203' => '3', '202206' => '5', '202207' => '4'], 
    'val2' => ['202201' => '54', '202202' => '43', '202203' => '12']
];

$perMonth = [];

foreach ($dataset as $metric => $weeklyData) {
    foreach ($weeklyData as $yearWeek => $value) {
        // 拆分年周为年份和周数
        $year = substr($yearWeek, 0, 4);
        $week = substr($yearWeek, 4, 2);
        
        // 将年周转换为对应日期,提取YYYY-MM格式的年月键
        $date = new DateTime();
        $date->setISODate($year, $week);
        $monthKey = $date->format('Y-m');
        
        // 初始化月份和指标的累加容器
        if (!isset($perMonth[$monthKey])) {
            $perMonth[$monthKey] = [];
        }
        if (!isset($perMonth[$monthKey][$metric])) {
            $perMonth[$monthKey][$metric] = 0;
        }
        
        // 累加数值(转换为数值类型避免字符串拼接)
        $perMonth[$monthKey][$metric] += (int)$value;
    }
}

// 按年月排序结果数组(可选)
ksort($perMonth);

print_r($perMonth);

关键细节说明

  • 年周转年月:使用setISODate方法可以可靠地将ISO标准的年周转换为对应日期,再提取年月格式。如果你的年周规则非ISO标准(如周起始日为周日),可以通过设置时区或调整DateTime参数适配。
  • 数值累加:必须将字符串类型的数值转换为int或float,否则会出现字符串拼接的错误结果。
  • 排序:最后用ksort对结果数组的年月键排序,保证输出顺序符合时间逻辑。

内容的提问来源于stack exchange,提问作者html5compiler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:06:32