Bill Bill - 11 months ago 41
JSON Question

Parse a decoded json array in PHP

I have a decoded json array which I received from the facebook API:

$Myposts = json_decode($response->getBody());

When I printed $Myposts :


It gived this :

public 'data' =>
array (size=24)
0 =>
public 'message' => string 'a mesagge..' (length=65)
public 'created_time' => string '2016-09-18T16:41:10+0000' (length=24)
public 'id' => string '111110037' (length=35)
1 =>
public 'message' => string 'How brave !' (length=11)
public 'story' => string 'XXX shared Le XX video.' (length=59)
public 'created_time' => string '2016-09-18T13:37:33+0000' (length=24)
public 'id' => string '102172976' (length=35)

23 =>
public 'message' => string '...a message..' (length=259)
public 'story' => string 'Bi added 3 new photos.' (length=33)
public 'created_time' => string '2015-12-11T20:54:21+0000' (length=24)
public 'id' => string '102191588' (length=35)
public 'paging' =>
public 'previous' => string '' (length=372)
public 'next' => string '' (length=362)

I'm new to php, and I don't have any idea how to deal with this output, I would like to loop through all the messages and output the created_time of each message.

Any ideas ?

EDIT : I tried :
echo $myPosts['data'][message];
from Parsing JSON file with PHP, but I have had : "Undefined index: message". That's why I posted a new question.

Answer Source

The second parameter of json_decode turns the result into an associative array:

$myPosts = json_decode($response->getBody(), true);

foreach ($myPosts['data'] as $post) {

Without using the second parameter the decoding returns objects:

$myPosts = json_decode($response->getBody());

foreach ($myPosts->data as $post) {