I've a nested JSON code as (it's actually my facebook status updates)
{
"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).
The json_encode() function is used to encode a value to JSON format.
The json_decode() function is used to decode or convert a JSON object to a PHP object.
You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type. Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value. When it is set as “true”, JSON objects are decoded into associative arrays.
Nested JSON is a JSON file with a big portion of its values being other JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.
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
}
You can use the json_decode
function to convert it to array and then iterate over the array using foreach
loop.
$array = json_decode($json, true);
foreach($array as $key => $value)
{
// your code....
}
The second option to json_decode
is whether or not you want to convert it to an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With