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

PHP如何统计JSON数据中每个需求对应各状态的出现次数

PHP实现方案

注意事项

你提供的原始内容是多个独立JSON对象的松散集合,不属于合法JSON格式,需要先在外层包裹[]将其转换为标准JSON数组后再解析。

完整实现代码

<?php
// 1. 构造/读取合法JSON(如果是从文件读取可以用file_get_contents('your_file.json')获取内容后补全括号)
$rawJsonFragment = <<<JSON
[
{
    "Requirement": "Name1",
    "Status": "Passed"
},
{
    "Requirement": "Name1",
    "Status": "Failed"
},
{
    "Requirement": "Name1",
    "Status": "Failed"
},
{
    "Requirement": "Name2",
    "Status": "Passed"
},
{
    "Requirement": "Name2",
    "Status": "Passed"
},
{
    "Requirement": "Name2",
    "Status": "Passed"
},
{
    "Requirement": "Name2",
    "Status": "Passed"
},
{
    "Requirement": "Name2",
    "Status": "Failed"
}
]
JSON;

// 2. 解析JSON为PHP关联数组
$recordList = json_decode($rawJsonFragment, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON解析错误:" . json_last_error_msg());
}

// 3. 统计每个需求的状态次数
$tempStats = [];
foreach ($recordList as $record) {
    $reqName = $record['Requirement'];
    $status = $record['Status'];
    // 初始化统计项
    if (!isset($tempStats[$reqName])) {
        $tempStats[$reqName] = [
            'Passed' => 0,
            'Failed' => 0
        ];
    }
    // 对应状态计数+1
    if (isset($tempStats[$reqName][$status])) {
        $tempStats[$reqName][$status]++;
    }
}

// 4. 转换为要求的关联数组格式
$result = [];
foreach ($tempStats as $name => $count) {
    $result[] = [
        'Name' => $name,
        'Passed' => $count['Passed'],
        'Failed' => $count['Failed']
    ];
}

// 输出验证结果
print_r($result);
?>

输出结果

运行上述代码后得到的$result数组结构和要求完全一致:

Array
(
    [0] => Array
        (
            [Name] => Name1
            [Passed] => 1
            [Failed] => 2
        )

    [1] => Array
        (
            [Name] => Name2
            [Passed] => 4
            [Failed] => 1
        )

)

内容的提问来源于stack exchange,提问作者Zoltán Seres

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:36:01