简体   繁体   English

json解码并使用PHP获得价值

[英]json decode and get value using PHP

I have a JSON string and i want to get the value. 我有一个JSON字符串,我想获取值。

$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;

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). ContextResponses包含一个数字索引的数组(仅包含一项),并且value属性比您要引用的内容嵌套得更深(位于属性数组中)。 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. 读取像这样的JSON序列化的数据结构时,您需要确保并记下每个开头[{因为它们对于需要如何引用其后的项目具有重要意义。 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. 您可能还需要在调查中考虑使用类似var_dump($result) ,因为这将向您显示反序列化后的数据结构,这通常使它更易于理解。

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. 使用http://jsonlint.com之类的内容来复制/粘贴JSON,以方便重新格式化。 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"
            }
        }
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM