如何使用foreach PHP访问JSON中的嵌套项?

时间:2015-10-21 11:28:47

标签: php json

我有以下JSON结构

{"Id":"1","Persons":[{"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}, {"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}{"Name":"Luis","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}]}

如何访问或读取嵌套内的项目?例如,如果我只想要Carl的时间价值或者有关Carl的所有信息。直到现在我可以毫无问题地收集集合'Id'中的单个项目。第一个嵌套的项目不是。 我尝试使用json_decode:

if( $_POST ) {

            $arr['Id'] = $_POST['Id'];
            $arr['NP'] = $_POST['NP'];

            $jsdecode = json_decode($arr);

            foreach ($jsdecode as $values){
                echo $values->Time;
            }

请问有人帮助我吗?

2 个答案:

答案 0 :(得分:5)

if( $_POST ) {

        $arr['Id'] = $_POST['Id'];
        $arr['NP'] = $_POST['NP'];

        $jsdecode = json_decode($arr,true);

        foreach ($jsdecode as $values){
            echo $values->Time;
        }

添加' true' to json_decode将其转换为数组

答案 1 :(得分:1)

您正在处理它是正确的,只需将true添加为json_decode的第二个参数,该参数将转换为 数组 ,如

$jsdecode = json_decode($arr,true);