php PHP解码嵌套的JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3555335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:12:39  来源:igfitidea点击:

PHP decode nested JSON

phpjsonfacebook

提问by ptamzz

I've a nested JSON code as (it's actually my facebook status updates)

我有一个嵌套的 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"
               }
            ],

         }
      }
]

Now how do I access the comments for a particular update and print it through a loop?? (I'm retrieving say a couple of updates at the same time).

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

回答by Lekensteyn

Use json_decode():

使用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
}

回答by Sarfraz

You can use the json_decodefunction to convert it to array and then iterate over the array using foreachloop.

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

$array = json_decode($json, true);

foreach($array as $key => $value)
{
  // your code....
}

The second option to json_decodeis whether or not you want to convert it to an array.

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