duan7264 2014-10-17 15:32
浏览 34
已采纳

json使用PHP解码并获取值

I have a JSON string and i want to get the value.

$s='{
"subscriptionId" : "51c04a21d714fb3b37d7d5a7",
"originator" : "localhost",
"contextResponses" : [
{
    "contextElement" : {
    "attributes" : [
      {
        "name" : "temperature",
        "type" : "centigrade",
        "value" : "26.5"
      }
    ],
    "type" : "Room",
    "isPattern" : "false",
    "id" : "Room1"
    },
     "statusCode" : {
     "code" : "200",
     "reasonPhrase" : "OK"
   }
 }
]
}';

Here is the code which I used but it didn't work.

$result = json_decode($s,TRUE); //decode json string
$b=$result ['contextResponses']['contextElement']['value']; //get the value????
echo $b;
  • 写回答

1条回答 默认 最新

  • duanchi19820419 2014-10-17 15:36
    关注

    ContextResponses contains a numerically indexed array (of only one item) and value property is more deeply nested than what you are trying to reference (it is within attributes array). This would appear to be what you need:

    $b = $result['contextResponses'][0]['contextElement']['attributes'][0]['value'];
    

    When reading a JSON-serialiazed data structure like that, you need to make sure and note every opening [ or { as they have significant meaning in regards to how you need to reference the items that follow it. You also may want to consider using something like var_dump($result) in your investigations, as this will show you the structure of the data after it has been deserialized, oftentimes making it easier to understand.

    Also, proper indention when looking at something like this would help. Use something like http://jsonlint.com to copy/paste your JSON for easy reformatting. If you had your structure like the following, nesting levels become more readily apparent.

    {
        "subscriptionId": "51c04a21d714fb3b37d7d5a7",
        "originator": "localhost",
        "contextResponses": [
            {
                "contextElement": {
                    "attributes": [
                        {
                            "name": "temperature",
                            "type": "centigrade",
                            "value": "26.5"
                        }
                    ],
                    "type": "Room",
                    "isPattern": "false",
                    "id": "Room1"
                },
                "statusCode": {
                    "code": "200",
                    "reasonPhrase": "OK"
                }
            }
        ]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?