【问题标题】:PHP decode nested JSONPHP解码嵌套JSON
【发布时间】:2010-08-24 10:03:15
【问题描述】:

我有一个嵌套的 JSON 代码(实际上是我的 Facebook 状态更新)

{
   "data": [
      {
         "id": "1290561400000000",
         "from": {
            "name": "My name",
            "id": "500920000"
         },
         "message": "Message body",
         "updated_time": "2010-08-24T08:22:13+0000",
         "comments": {
            "data": [
               {
                  "id": "129056140474641_8000",
                  "from": {
                     "name": "name1",
                     "id": "100000486072000"
                  },
                  "message": "hahahahahahha..........",
                  "created_time": "2010-08-24T08:40:39+0000"
               },
               {
                  "id": "129056140474641_8000000",
                  "from": {
                     "name": "name2",
                     "id": "1597542457"
                  },
                  "message": "true ya. I have updated",
                  "created_time": "2010-08-24T08:59:53+0000"
               },
               {
                  "id": "129056140474641_83000",
                  "from": {
                     "name": "Name3",
                     "id": "1000004860700000"
                  },
                  "message": "am putting it on my wall....",
                  "created_time": "2010-08-24T09:01:25+0000"
               }
            ],

         }
      }
]

现在我如何访问特定更新的 cmets 并通过循环打印它? (我正在同时检索几个更新)。

【问题讨论】:

    标签: php json facebook


    【解决方案1】:

    使用json_decode():

    $decoded = json_decode($json_string);
    $comments = $decoded->data[0]->comments->data;
    foreach($comments as $comment){
       $name = $comment->from->name;
       $message = $comment->message;
       //do something with it
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用json_decode 函数将其转换为数组,然后使用foreach 循环遍历数组。

      $array = json_decode($json, true);
      
      foreach($array as $key => $value)
      {
        // your code....
      }
      

      json_decode 的第二个选项是是否要将其转换为数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-30
        • 1970-01-01
        • 1970-01-01
        • 2021-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多