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"
                }
            }
        ]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源