访问多维JSON对象中的数据

时间:2015-04-03 17:55:34

标签: php json

我在$result变量的API调用中返回了以下JSON对象,我的问题是我需要访问每个列表中的"name"项,但它没有工作

{
"status": "success",
"data": {
    "lists": [
        {
            "id": "0032",
            "name": "Stan",
            "status": "active",                
        },
        {
            "id": "0043",
            "name": "David",
            "status": "active",                
        },
        {
            "id": "2323",
            "name": "Robert",
            "status": "pending",                
        }
    ]
}
}

代码:

 if (isset($result)) {
        $json_object = json_decode($result, true);
        echo $json_object['status'];
        echo $result;

        if ($json_object['status'] == 'success') {
            $json_object2 = $json_object['data'];
            foreach ($json_object['data'] as $key => $value){                                   
                foreach ($value as $key2 => $value2){
                    echo $key2 . " : " . $value2 . "</br>";
                }
            }   
        } else {
            echo $json_object['data'];
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

<?php

$result = '{"status":"success","data":{"lists":[{"id":"0032","name":"Stan","status":"active"},{"id":"0043","name":"David","status":"active"},{"id":"2323","name":"Robert","status":"pending"}]}}';

$json_object = json_decode($result, true);

foreach($json_object['data']['lists'] as $item)
{
    echo $item['name']."<br>";
}

?>