You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP统计多JSON文件hours字段总和返回0如何解决?

问题原因排查方向

  • 路径匹配失败:glob('data/*.json') 返回空数组。大概率是执行PHP脚本时的工作目录和你预期的不一致,导致找不到data目录下的JSON文件,$files为空,后续没有任何数值被累加,$total_hours保持初始值0。
  • 数组未初始化:你没有提前声明$hours_arrays = [],如果$files为空,该数组不会被创建,后续遍历空值不会触发累加逻辑。
  • JSON解析失败:部分JSON文件格式不合法,json_decode返回null,此时$val['hours']取值为null,累加时被转为0,不会贡献总和。
  • 字段缺失:部分JSON文件不存在hours字段,同样取值为null,累加无贡献。

修复后的代码

// 初始化数组避免未定义警告
$hours_arrays = [];
// 用绝对路径避免相对路径匹配失败,__DIR__是当前脚本所在目录
$files = glob(__DIR__ . '/data/*.json');
if (!empty($files)) {
    foreach($files as $file) {
        $content = file_get_contents($file);
        $data = json_decode($content, true);
        // 校验解析结果和字段存在性
        if (json_last_error() === JSON_ERROR_NONE && isset($data['hours']) && is_numeric($data['hours'])) {
            $hours_arrays[] = $data;
        }
    }
}

$total_hours = 0;
foreach($hours_arrays as $val) {
    $total_hours += $val['hours'];
}

echo $total_hours;

内容的提问来源于stack exchange,提问作者john

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:24:03