如何简化JSON数组pet_type统计并转为指定格式字符串?
简化JSON宠物类型统计输出的方法
嘿,你的需求我get到了——把给定的JSON宠物数据转换成3 Dogs, 2 Cats这种简洁的统计字符串对吧?你当前的实现思路(提取pet_type存数组、用array_count_values统计、再foreach拼接)完全可行,但确实可以优化掉显式的foreach循环,让代码更紧凑。下面给你两种实现思路:
方法一:组合array_column + array_count_values + array_map + implode
这种方法把数据提取、统计、字符串转换和拼接串在一起,全程不需要手动写循环:
$json = '[ {"pet_type":"Dog","weight":"26","description":"Akita"}, {"pet_type":"Dog","weight":"6","description":"Pug"}, {"pet_type":"Cat","weight":"4","description":"Manx"}, {"pet_type":"Dog","weight":"12","description":"Beagle"}, {"pet_type":"Cat","weight":"5","description":"Siberian"} ]'; // 一步完成解析、统计、转换和拼接 $result = implode(', ', array_map( function($type, $count) { return "$count " . str_plural($type, $count); }, array_keys($counts = array_count_values(array_column(json_decode($json, true), 'pet_type'))), $counts )); echo $result; // 输出:3 Dogs, 2 Cats
步骤拆解:
json_decode($json, true):把JSON字符串转成PHP关联数组array_column(..., 'pet_type'):提取所有宠物类型,得到数组['Dog', 'Dog', 'Cat', 'Dog', 'Cat']array_count_values(...):统计每种类型的数量,得到['Dog' => 3, 'Cat' => 2]array_map(...):把类型和数量配对,生成每个统计项的字符串(比如"3 Dogs")implode(', ', ...):把所有统计项用,连接成最终字符串
方法二:用array_reduce直接统计+后续转换
如果想更直接地遍历原始数据完成统计,可以用array_reduce,同样不需要显式循环:
$json = '[ {"pet_type":"Dog","weight":"26","description":"Akita"}, {"pet_type":"Dog","weight":"6","description":"Pug"}, {"pet_type":"Cat","weight":"4","description":"Manx"}, {"pet_type":"Dog","weight":"12","description":"Beagle"}, {"pet_type":"Cat","weight":"5","description":"Siberian"} ]'; $result = implode(', ', array_map( function($item) { return "{$item[1]} " . str_plural($item[0], $item[1]); }, array_reduce(json_decode($json, true), function($carry, $item) { // 累加每种宠物的数量 $carry[$item['pet_type']] = ($carry[$item['pet_type']] ?? 0) + 1; return $carry; }, []) )); echo $result; // 输出:3 Dogs, 2 Cats
这种方法用array_reduce遍历解析后的数组,直接完成数量统计,后续的array_map和implode和第一种方法逻辑一致,同样避免了手动写foreach。
两种方法都能达到你的需求,代码更简洁,也符合PHP的函数式编程风格~
内容的提问来源于stack exchange,提问作者niksrb
相关产品推荐
相关产品推荐

