PHP统计JSON数组中status id为4的对象出现次数
PHP统计status.id为4的房产总数实现方案
原有代码的问题
- 仅读取了JSON中下标为0的第一个客户数据,没有覆盖所有客户对象
- 只统计了数组总长度,没有对
status.id = 4的条件做过滤 - 存在隐性报错风险:
json_decode默认返回stdClass对象,无法直接用方括号下标访问属性,原代码写法不加额外参数会触发类型警告
兼容原有写法的实现代码
将json_decode 加第二个参数true转成关联数组,匹配你习惯的下标访问风格:
$content = file_get_contents('estateList/estateList.json'); $estateList = json_decode($content, true); // 统一维护需要统计的房产分类,避免重复写判断逻辑 $estateCategories = ['houses', 'plots', 'projects', 'farms', 'commercialPropertys', 'condominiums', 'foreignProperties', 'premises']; $soldTotal = 0; // 遍历所有客户对象 foreach ($estateList as $customer) { // 遍历当前客户下的所有房产分类 foreach ($estateCategories as $category) { // 跳过空的分类数组 if (empty($customer[$category])) continue; // 遍历分类下的单条房产记录 foreach ($customer[$category] as $estate) { // 判断status.id是否为字符串格式的'4',注意和整数4做类型区分 if (isset($estate['status']['id']) && $estate['status']['id'] === '4') { $soldTotal++; } } } } // $soldTotal 即为最终统计结果 echo "符合条件的房产总数量:" . $soldTotal;
更精简的写法
用内置的array_filter 替代三层foreach的内层判断,代码更短:
$content = file_get_contents('estateList/estateList.json'); $estateList = json_decode($content, true); $estateCategories = ['houses', 'plots', 'projects', 'farms', 'commercialPropertys', 'condominiums', 'foreignProperties', 'premises']; $soldTotal = 0; foreach ($estateList as $customer) { foreach ($estateCategories as $category) { // 过滤出分类下status.id为4的记录,累加计数 $soldTotal += count(array_filter( $customer[$category] ?? [], function($estate) { return ($estate['status']['id'] ?? '') === '4'; } )); } }
注:如果是PHP7.4及以上版本,可以把匿名函数换成更简洁的箭头函数fn($estate) => ($estate['status']['id'] ?? '') === '4'
注意事项
- JSON中的
status.id是字符串格式的"4",做严格相等判断时不要用整数4,避免类型不匹配导致统计遗漏 - 代码中通过
isset做了字段存在性判断,可避免部分房产缺少status字段时触发报错
内容的提问来源于stack exchange,提问作者djsringup
相关产品推荐
相关产品推荐

