【问题标题】:How to access array in array?如何访问数组中的数组?
【发布时间】:2016-11-12 21:30:18
【问题描述】:

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

这是我从 Facebook Graph Api 获得的 JSON 的 print_r

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

任何帮助表示赞赏!

【问题讨论】:

  • $array['key']['subkey']['subsubkey']
  • $decoded['posts']['data'][0]['message']
  • 感谢大家的帮助!

标签: php json facebook-graph-api server


【解决方案1】:

你可以简单地跟随数组的键:

$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的信息。

希望对您有所帮助!

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
相关资源
最近更新 更多