PHP中按file_format与language组合统计JSON数组元素数量的方法
解决PHP中按多字段分组统计数组的问题
我明白你遇到的问题啦——array_count_values确实没法直接满足你的需求,因为它只能处理一维数组的单值统计,而你需要按file_format和language两个字段的组合来分组计数。下面给你两种可行的实现方式:
方法一:遍历数组手动分组统计
这是最直观的方式,通过遍历原数组,用两个字段的组合作为唯一键来统计数量:
// 原始JSON数据 $jsonData = '[{"id":447,"file_format":"abc","language":"af"},{"id":449,"file_format":"abc","language":"af"},{"id":453,"file_format":"abc","language":"afs"},{"id":454,"file_format":"def","language":"afs"}]'; // 解码为PHP关联数组 $originalArray = json_decode($jsonData, true); // 初始化分组统计数组 $groupedData = []; foreach ($originalArray as $item) { // 用file_format和language拼接成唯一标识键 $uniqueKey = $item['file_format'] . '|' . $item['language']; if (isset($groupedData[$uniqueKey])) { // 已存在该组合,计数加1 $groupedData[$uniqueKey]['count']++; } else { // 首次出现该组合,初始化条目 $groupedData[$uniqueKey] = [ 'file_format' => $item['file_format'], 'language' => $item['language'], 'count' => 1 ]; } } // 提取关联数组的value,转为索引数组(符合目标格式) $resultArray = array_values($groupedData); // 转成JSON输出 $resultJson = json_encode($resultArray); print_r($resultJson);
方法二:使用array_reduce简化代码
如果你喜欢更简洁的函数式写法,可以用array_reduce来实现相同的逻辑:
$jsonData = '[{"id":447,"file_format":"abc","language":"af"},{"id":449,"file_format":"abc","language":"af"},{"id":453,"file_format":"abc","language":"afs"},{"id":454,"file_format":"def","language":"afs"}]'; $originalArray = json_decode($jsonData, true); $groupedData = array_reduce($originalArray, function($carry, $item) { $uniqueKey = $item['file_format'] . '|' . $item['language']; if (!isset($carry[$uniqueKey])) { $carry[$uniqueKey] = [ 'file_format' => $item['file_format'], 'language' => $item['language'], 'count' => 0 ]; } $carry[$uniqueKey]['count']++; return $carry; }, []); $resultArray = array_values($groupedData); $resultJson = json_encode($resultArray); print_r($resultJson);
两种方法最终都会输出你想要的结果:
[{"file_format":"abc","count":2,"language":"af"},{"file_format":"abc","count":1,"language":"afs"},{"file_format":"def","count":1,"language":"afs"}]
核心思路都是用两个字段的组合作为唯一标识,以此来区分不同的分组,然后统计每个分组下的元素数量。这样就能完美替代array_count_values无法处理多字段分组的局限啦~
内容的提问来源于stack exchange,提问作者Chirag Kohli
相关产品推荐
相关产品推荐

