使用PHP解析JSON数组不起作用

时间:2016-07-08 01:36:27

标签: php arrays json parsing

从服务请求我得到以下响应,我已经尝试json_decode来解析它,但它不起作用。我需要检查一下 ["body"]->enquiry->status是“开放”。谁能告诉我如何解析这个回复?

array(5) {
    ["headers"] => array(5) {
        ["server"] => string(17)
        "Apache-Coyote/1.1" ["content-type"] => string(16)
        "application/json" ["content-length"] => string(3)
        "313" ["date"] => string(29)
        "Fri, 08 Jul 2016 00:22:29 GMT" ["connection"] => string(5)
        "close"
    }
    ["body"] => string(313){
        "version ":{
            "major ":1,
            "minor ":6,
            "revision ":0
        },
        "enquiry ":{
            "id ":"21a2a688-c09b-48bc-8cb0-0ad596c18447",
            "creationTime ":1467937344745,
            "lastUpdateTime ":1467937344753,
            "status ":"OPEN ",
            "from ":"test ",
            "email ":"test@mailinator.com ",
            "message ":"test ",
        },
        "enquiries":null
    } 
    ["response"] => array(2) {
        ["code"] => int(202)
        ["message"] => string(8)
        "Accepted"
    }
    ["cookies"] => array(0) {}
    ["filename"] => NULL
}

1 个答案:

答案 0 :(得分:1)

以下是如何访问它。我使用$response作为您给我们的回复。

//We decode the 'body' from the response to json and we convert it to an array
$body = json_decode($response['body'],true);

//We access the status
$status = $body['enquiry']['status'];

另外,如果要检查状态是否等于“打开”,请务必小心。在您的回复中,状态为实际OPEN。注意尾随空格。您可以使用trim($status)删除空格。