如何访问数组中的数组?

时间:2016-11-12 21:30:18

标签: php json facebook-graph-api server

如何从Facebook Graph Api访问帖子数据,如[message]和[created_time]?

这是JSON的print_r,我从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
)

我的PHP代码:

$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);

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

您只需按照数组的键即可:

$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']

更好的是,您可以循环浏览$decoded['posts']['data'],如此:

$decoded = json_decode($data, true);

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

详细了解PHP Array here

希望这有帮助!