Lucy Weatherford
Lucy Weatherford

Reputation: 5534

Facebook Graph API mutual friends

Using Facebook graph API, I am trying to retrieve number of mutual friends 2 users have. However, I am getting number of friends of one of them instead.

Here is my code:

    <?php

    $mutual_array = json_decode(file_get_contents("https://graph.facebook.com/".$fb_id."/mutualfriends/".$other_fb_id."?".$access_token), true);

    $mutual_friends = $mutual_array['data'];
    $mutual_number = count($mutual_friends);

    ?>

$mutual_number gives the number of facebook friends $other_fb_id user has. And when I try to print_r $mutual_friends it gives all the friends the user has.

Anyone know what's going on here? Thanks.

Upvotes: 2

Views: 3132

Answers (6)

Lior Nitzan
Lior Nitzan

Reputation: 68

You forgot the access_token= param:

$mutual_array = json_decode(file_get_contents("https://graph.facebook.com/".$other_fb_id."/mutualfriends/".$fb_id."?access_token=".$access_token), true);

Upvotes: 0

Soojoo
Soojoo

Reputation: 2156

The answer is simple. The only thing you do is to change the order of placing your facebook id and friend's facebook id:

$mutual_array = json_decode(file_get_contents("https://graph.facebook.com/".$other_fb_id."/mutualfriends/".$fb_id."?".$access_token), true);

Upvotes: 1

user1105951
user1105951

Reputation: 2287

With graph api it's done by requesting :

me/mutualfriends?user=SOME_USER_ID

if you and the SOME_USER_ID have mutualfriends you get the list of friends.

Upvotes: 0

Lucy Weatherford
Lucy Weatherford

Reputation: 5534

This is a facebook api bug. Even though the information is symetrical, to get the number of mutual friends, you have to use the access token of the current user (user a), not of the other user you are checking with.

Upvotes: 0

mrtom
mrtom

Reputation: 2156

Sounds like both your user id's are the same. Are you 100% sure they're not??

Upvotes: 0

Inam Abbas
Inam Abbas

Reputation: 1480

In your code above $fb_id must have to be currently login user ID or it must be your application user. Facebook api do not allow to get mutual friends of any x-y-z user until they have joined your application.

Test it in fb explorer

Alternatively if you have friends of both users you can use array_intersect function of PHP to get common ids from both friends array.

$result = array_intersect($user1_friends_array, $user2_friends_array);
print_r($result);

Upvotes: 1

Related Questions