3

私がしようとしているのは、PHPでfacebookの友達のカウンターです。その結果、コードの結果は "You have 1342 Friends!"のようになります。Facebook friend counter

<?php 

require_once("../src/facebook.php"); 

    $config = array(); 
    $config[‘appId’] = 'MY_APP_ID'; 
    $config[‘secret’] = 'MY_APP_SECRET'; 
    $facebook = new Facebook($config); 
    $user_id = "MY_USER_ID"; 

     //Get current access_token 
    $token_response = file_get_contents 
     ("https://graph.facebook.com/oauth/access_token? 
     client_id=$config[‘appId’] 
     &client_secret=$config[‘secret’] 
     &grant_type=client_credentials"); 


    // known valid access token stored in $token_response 
    $access_token = $token_response; 

    $code = $_REQUEST["code"]; 

    // If we get a code, it means that we have re-authed the user 
    //and can get a valid access_token. 
    if (isset($code)) { 
    $token_url="https://graph.facebook.com/oauth/access_token?client_id=" 
     . $app_id 
     . "&client_secret=" . $app_secret 
     . "&code=" . $code . "&display=popup"; 
    $response = file_get_contents($token_url); 
    $params = null; 
    parse_str($response, $params); 
    $access_token = $params['access_token']; 
    } 


    // Query the graph - Friends Counter: 
$data = file_get_contents 
("https://graph.facebook.com/$user_id/friends?" . $access_token); 
$friends_count = count($data['data']); 
echo "Friends: $friends_count"; 

echo "<p>$data</p>"; //to test file_get_contents 

?> 

ので、エコー$ Friends_countの結果その常に "1":

は、これは使用してコードイムです。

そしてエコーで$データをテストすると、それはコンテンツを取得しているので、すべての友人のリストを私に与えますが、それは正しくカウントされません...どのように私はそれを修正することができますか?

私はすでに

$friends_count = count($data['name']); 

$friends_count = count($data['id']); 

ため

$friends_count = count($data['data']); 

を変更しようとしましたが、結果は常に "1" です。


上記コードの結果は次のようになります。

Friends: 1 

{"data":[{"name":"Enny Pichardo","id":"65601304"},{"name":"Francisco Roa","id":"500350497"},etc...] 
+1

あなたはそれが前にそれを感謝の –

+0

http://stackoverflow.com/a/4066229/1100237 – coppettim

答えて

2

あなたにはJSONオブジェクトがあります。文字列で、PHPがcount()で「数える」ことはできません。あなたはJSONが最初に解析する必要があります。

$obj=json_decode($data); 
$friends_count = count($obj->data); // This refers to the "data" key in the JSON 

私はすぐにGoogleでいくつかの参照:

http://php.net/manual/en/function.json-decode.php
http://roshanbh.com.np/2008/10/creating-parsing-json-data-php.html

+0

百万を数える()json_decodeする必要があります!それは問題を解決する! JSONオブジェクトについて新しいことはもうありませんでした。 – Hawk

0

あなたは簡単にFQLで友人数を取得することができます。

照会できるuserテーブルに対するfriend_countフィールドがあります。

SELECT friend_count FROM user WHERE uid = me(); 

https://graph.facebook.com/fql?q=SELECT friend_count FROM user WHERE uid={any id}