PHP数组计算:2019年各月与前5个月数值求和
解决PHP数组中2019年每月与前5个月数值求和的问题
看起来你在处理日期数组的滚动求和时遇到了麻烦,我来帮你梳理下问题并给出可行的解决方案。
先明确你的核心需求:
- 仅针对数组中2019年的所有月份(
date_2019_01到date_2019_12)进行计算 - 每个月的结果 = 当前月数值 + 往前推5个月的数值总和(总共6个月的数值相加)
- 已经对原数组执行了
krsort($array)排序(从最新日期到最旧日期排列)
原数组与期望示例
你的原数组如下:
$array = array( "date_2019_12" => 0, "date_2019_11" => 0, "date_2019_10" => 0, "date_2019_09" => 0, "date_2019_08" => 0, "date_2019_07" => 0, "date_2019_06" => 0, "date_2019_05" => 0, "date_2019_04" => 0, "date_2019_03" => 0, "date_2019_02" => 0, "date_2019_01" => 10, "date_2018_12" => 1, "date_2018_11" => 2, "date_2018_10" => 3, "date_2018_09" => 4, "date_2018_08" => 5, "date_2018_07" => 6, ); krsort($array); // 排序后数组从date_2019_12到date_2018_07排列
你期望的计算逻辑示例:
date_2019_01=> 25(10+1+2+3+4+5,2019年1月的10加上2018年8-12月的数值)date_2019_02=> 20(0+10+1+2+3+4,2019年2月的0加上2019年1月的10,再加上2018年9-12月的数值)date_2019_03=> 16(0+0+10+1+2+3,以此类推)- …一直到
date_2019_12
你尝试的代码问题分析
你之前写的代码存在几个关键问题:
- 循环逻辑混乱,没有实现数值累加,反而在重复赋值数组元素
- 未处理月份跨年份的情况(比如2019年1月往前推5个月是2018年8月)
- 没有针对2019年的月份做过滤,会误处理2018年的月份
修正后的解决方案
下面是完整的可运行代码,包含详细注释:
$array = array( "date_2019_12" => 0, "date_2019_11" => 0, "date_2019_10" => 0, "date_2019_09" => 0, "date_2019_08" => 0, "date_2019_07" => 0, "date_2019_06" => 0, "date_2019_05" => 0, "date_2019_04" => 0, "date_2019_03" => 0, "date_2019_02" => 0, "date_2019_01" => 10, "date_2018_12" => 1, "date_2018_11" => 2, "date_2018_10" => 3, "date_2018_09" => 4, "date_2018_08" => 5, "date_2018_07" => 6, ); // 提取2019年的所有月份键,并按升序排列(从01到12) $year2019Keys = array_filter(array_keys($array), function($key) { return strpos($key, 'date_2019_') === 0; }); sort($year2019Keys); $newArr = array(); foreach ($year2019Keys as $currentKey) { // 拆分当前键,获取年份和月份 list($prefix, $year, $month) = explode('_', $currentKey); $currentMonth = (int)$month; $currentYear = (int)$year; $total = 0; // 循环计算当前月 + 前5个月,共6个月的数值总和 for ($i = 0; $i <= 5; $i++) { $targetMonth = $currentMonth - $i; $targetYear = $currentYear; // 处理月份小于1的跨年份情况(比如2019年1月-1个月=2018年12月) if ($targetMonth < 1) { $targetYear--; $targetMonth += 12; } // 格式化月份为两位数字(比如1转为01) $formattedMonth = str_pad($targetMonth, 2, '0', STR_PAD_LEFT); $targetKey = "{$prefix}_{$targetYear}_{$formattedMonth}"; // 累加数值,不存在的键默认取0 $total += isset($array[$targetKey]) ? $array[$targetKey] : 0; } $newArr[$currentKey] = $total; } // 输出结果 print_r($newArr);
代码关键说明
- 过滤排序:用
array_filter提取2019年的所有键,再用sort按升序排列,确保从1月到12月顺序处理 - 跨月处理:针对每个月份,循环计算往前0-5个月的日期,自动处理跨年份的月份转换
- 安全取值:检查目标键是否存在,避免未定义索引错误,不存在的键默认取0
运行结果
执行代码后会得到符合你预期的结果:
Array ( [date_2019_01] => 25 [date_2019_02] => 20 [date_2019_03] => 16 [date_2019_04] => 13 [date_2019_05] => 11 [date_2019_06] => 10 [date_2019_07] => 10 [date_2019_08] => 10 [date_2019_09] => 10 [date_2019_10] => 10 [date_2019_11] => 10 [date_2019_12] => 10 )
内容的提问来源于stack exchange,提问作者S S
相关产品推荐
相关产品推荐

