重新格式化从Facebook Open Graph解码的PHP数组

时间:2012-04-15 19:46:12

标签: php arrays json facebook-graph-api

我设计的应用程序将受益于用户的Facebook好友在打字时向他们建议。我遇到的困难是将Open Graph结果(通过graph.facebook.com/me访问用户朋友时)转换为AutoSuggest jQuery插件所需的格式。

我知道我可以使用$user = json_decode(file_get_contents($graph_url));将此JSON结果解码为数组,但我没有经验丰富的PHP来访问此数组的部分并将其置于以下格式。

所需格式:["First Friend","Second Friend","Third Friend"]

当前格式:( [data] => Array ( [0] => ( [name] => Ryan Brodie [id] => 740079895 ) ) [paging] => ( [next] => https://graph.facebook.com/me/friends?access_token=ACCESS_TOKEN&limit=5000&offset=5000&__after_id=USERID ) )

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

$user = json_decode(file_get_contents($graph_url));
$friends = array();
foreach($user['data'] as $friend) {
  if (! empty($friend['name'])) {
    $friends[] = $friend['name'];
  }
}

print_r($friends);

答案 1 :(得分:0)

Zombat的答案几乎是正确的

$user = json_decode(file_get_contents($graph_url));
$friends = array();
foreach($user->data as $friend) {
    $friends[] = $friend->name;
}

echo json_encode($friends);