PHP decodes embedded JSON

I have a nested JSON code (it actually updates my status)

{ "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 specific update and print it through a loop? (I get a couple of updates at the same time).

+6
json php facebook
source share
2 answers

Use 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 } 
+16
source share

You can use the json_decode function to convert it to an array, and then iterate through the array using a foreach .

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

The second option to json_decode is whether you want to convert it to an array.

+2
source share

All Articles