首页 > 解决方案 > php解析JSON子数组

问题描述

我在 PHP 中有一个 JSON 字符串:

$casedata = "{\"id\":4823,\"status\":2,\"steps\":12,\"error\":\"catched error playing testcase\",\"result\":\"\",\"sublog\":[{\"step\":8,\"message\":\"corpus.invalidState.2.getBlockedRegionsForUnit\"},{\"step\":10,\"message\":\"corpus.invalidState.2.getBlockedRegionsForUnit\"}]}";

我尝试用

$array = json_decode($casedata,true);

不,我通过以下键遍历:

foreach($array as $key => $value){
        if(is_array($value)){
            echo "Array";
        }else{
            echo "Content: ".$key." / ".$value." <br/>";
        }
}

输出是

Content: id / 4823
Content: status / 2
Content: steps / 12
Content: error / catched error playing testcase 
Content: result /
Array

工作正常。但是如何从子数组“sublog”中获取 $key 和 $value 呢?我试过作为样本:

foreach($array as $key => $value){
        if(is_array($value)){
            echo "Array";
            foreach($value as $sub => $value2){
                echo "Sub: ".$sub." / ".$value2." <br/>";
            }
        }else{
            echo "Content: ".$key." / ".$value." <br/>";
        }
}

但这不起作用。我在这里想念什么?

标签: phpjson

解决方案


您的内部数组是一维数组,而不是关联数组。

尝试使用

foreach($array as $key => $value){
        if(is_array($value)){
            echo "Array";
            $count = count($value);
            for($i=0;i<$count;i++) {
                echo $value[i]['step']; // <---
             }
        }
    }else{
        echo "Content: ".$key." / ".$value." <br/>";
    }
}

推荐阅读