Gintas Gintas - 22 days ago 6
JSON Question

How to access array in array?

how can i access posts data, like [message] and [created_time] from Facebook Graph Api?

Here is the print_r of JSON , which I'm getting from Facebook Graph Api

Array
(
[posts] => Array
(
[data] => Array
(
[0] => Array
(
[message] => random message.
[created_time] => 2016-11-12T07:26:23+0000
[id] => id786456786
)
[1] => Array
(
[message] => random message.
[created_time] => 2016-11-11T04:30:02+0000
[id] => id123456768
)
)
[paging] => Array
(
[previous] => https://graph.facebook.com/v2.8/pageid/posts?limit=2&since=1478935583&access_token=MY ACCESS TOKEN ....
)
)
[id] => id
)


My php code:

$data = file_get_contents("https://graph.facebook.com/v2.8facebookpageid?fields=posts.limit(2)&access_token=MY_ACCESS_TOKEN");

$decoded = json_decode($data,true);

print_r($decoded);


Any help appreciated!

Answer

You can just simply follow the array's key:

$decoded = json_decode($data, true);

// Retrieve the first message.
$message = $decoded['posts']['data'][0]['message']

// Retrieve the second message.
$message = $decoded['posts']['data'][1]['message']

Even better, you can loop through the $decoded['posts']['data'] like so:

$decoded = json_decode($data, true);

foreach ($decoded['posts']['data'] as $item) {
    echo "Message: {$item['message']}\n";
    echo "Created Time: {$item['created_time']}\n";
}

Read more about PHP Array here.

Hope this help!

Comments