PHP / Facebook-Api:更新好友列表

时间:2010-12-17 20:41:56

标签: php facebook-graph-api

我正在使用官方的PHP-Facebook-Api,我知道如何获取用户的好友列表。它基本上是这样的:

    $facebook = new Facebook(array(
                'appId' => 'xxxxxxxx',
                'secret' => 'xxxxxxx',
                'cookie' => true,
            ));
    // $session is only != null, when you have the session-cookie, that is set by facebook, after the user logs in
    $session = $facebook->getSession(); 
    // you dont get a list of friends, but a list, which contains other friendlists
    $friendsLists = $facebook->api('/me/friends');

    // Save all Friends and FriendConnections
    foreach ($friendsLists as $friends) {
      foreach ($friends as $friend) {
         // do something with the friend, but you only have id and name
         $id = $friend['id'];
         $name = $friend['name'];
      }
   }

在我的应用程序中,我基本上将所有朋友保存在我的数据库中,这样我每次想要显示所有用户的朋友时都不会发出http请求。但现在我想更新好友列表。我不想删除所有的朋友 - 连接并重新保存它们。那么有人知道一个选项,如何在特定日期之后获取好友列表的更改?

1 个答案:

答案 0 :(得分:2)

然后你必须检查它们是否在数据库中。我建议您获取数据库中所有用户ID的数组,然后针对您从API中提取的朋友进行检查。如果有新朋友,请添加它们。

$database = new mysqli('Localhost', 'username', 'password', 'db_name');

if($users = $database->query('SELECT id FROM `users`')) {
    while($row = $result->fetch_assoc()) {
        $my_friend[] = $row['id'];
    }
}

$facebook = new Facebook(array(
            'appId' => 'xxxxxxxx',
            'secret' => 'xxxxxxx',
            'cookie' => true,
        ));
// $session is only != null, when you have the session-cookie, that is set by facebook, after the user logs in
$session = $facebook->getSession(); 
// you dont get a list of friends, but a list, which contains other friendlists
$friendsLists = $facebook->api('/me/friends');

// Save all Friends and FriendConnections
foreach ($friendsLists as $friends) {
  foreach ($friends as $friend) {
     // do something with the friend, but you only have id and name
     $id = $friend['id'];
     $name = $friend['name'];

     if(!in_array($id, $my_friends)) {
        // Insert into table
     }
  }
}