Skip to content

Instantly share code, notes, and snippets.

@jelmervdl
Created January 8, 2012 10:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jelmervdl/1577946 to your computer and use it in GitHub Desktop.
Save jelmervdl/1577946 to your computer and use it in GitHub Desktop.
Find mutual friends of your friends.
<?php
class FacebookAPI
{
protected $_token;
public function __construct($token)
{
$this->_token = $token;
}
public function friends($id)
{
$this->_requestPaged('https://graph.facebook.com/' . $id . '/friends?format=json');
}
protected function _request($url)
{
$response = file_get_contents($url . '&access_token=' . $this->_token);
if (!$response)
throw new Exception("Request to {$url} failed miserably");
return json_decode($response);
}
protected function _requestPaged($url)
{
$data = array();
// while there are still more pages to fetch..
while ($url)
{
$response = $this->_request($url);
// if there is no more data, stop.
if (!count($response->data))
break;
$data = array_merge($data, $response->data);
$url = isset($response->paging, $response->paging->next)
? $response->paging->next
: null;
}
return $data;
}
}
function find_mutual_friends($users)
{
$friends = array();
$facebook = new FacebookAPI('...');
foreach ($users as $user)
{
foreach ($facebook->friends($user) as $friend)
{
if (isset($friends[$friend->id]))
$friends[$friend->id]->count++;
else
$friends[$friend->id] = build_friend($friend);
}
}
// sort on how many mutual friends he has.
usort($friends, function($a, $b) {
return compare_int($a->count, $b->count);
});
return $friends;
}
function compare_int($a, $b)
{
if ($a == $b)
return 0;
else
return $a > $b ? 1 : -1;
}
function build_friend($friend)
{
$friend->count = 1;
return $friend;
}
var_dump(find_mutual_friends(array(...)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment