如何统计数组中同月份条目数?附用户增长月报场景示例
嘿,这个需求太常见了——做月度增长报表肯定要搞这种日期分组统计对吧?我给你两种实用的PHP实现方式,你按需选:
方法一:遍历数组手动分组计数
这种方法逻辑直白,新手也能一眼看懂:
$dates = array('2017-03-24 01:48:09', '2017-03-24 11:48:09', '2017-04-07 01:12:19', '2017-04-14 01:49:09', '2017-04-21 01:45:09', '2017-04-28 01:38:09'); // 初始化空数组存月份计数 $monthCount = []; foreach ($dates as $dateStr) { // 用DateTime解析日期,提取「年-月」作为唯一标识(避免跨年份同月混算) $date = new DateTime($dateStr); $monthKey = $date->format('Y-m'); // 计数累加:已存在就+1,不存在就初始化为1 if (isset($monthCount[$monthKey])) { $monthCount[$monthKey]++; } else { $monthCount[$monthKey] = 1; } } // 打印结果 print_r($monthCount);
运行后会得到:
Array ( [2017-03] => 2 [2017-04] => 4 )
这里用Y-m当键是为了区分不同年份的同月(比如2017年3月和2018年3月),如果你的报表只需要月份名称/数字,改成format('F')(中文环境下是「三月」「四月」)或format('m')(「03」「04」)就行,按需调整。
方法二:用array_reduce简化代码
如果喜欢更紧凑的函数式写法,用array_reduce可以一步完成分组统计:
$dates = array('2017-03-24 01:48:09', '2017-03-24 11:48:09', '2017-04-07 01:12:19', '2017-04-14 01:49:09', '2017-04-21 01:45:09', '2017-04-28 01:38:09'); $monthCount = array_reduce($dates, function($carry, $dateStr) { $monthKey = (new DateTime($dateStr))->format('Y-m'); $carry[$monthKey] = isset($carry[$monthKey]) ? $carry[$monthKey] + 1 : 1; return $carry; }, []); print_r($monthCount);
结果和方法一完全一致,只是把循环逻辑封装到了array_reduce里,代码更简洁。
内容的提问来源于stack exchange,提问作者Crys
相关产品推荐
相关产品推荐

