3

私がやろうとしているのは、PHP で Facebook の友達のカウンターを作成することなので、コードの結果は "You have 1342 Friends!" のようなものになります。

だから、これは私が使用しているコードです:

<?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

?>

したがって、echo $Friends_count の結果は常に「1」になります。

そして、エコーで$dataをテストすると、すべての友達のリストが表示されるので、コンテンツを取得していますが、正しくカウントされていません...どうすれば修正できますか?

私はすでに変更しようとしました

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

為に

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

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

ただし、結果は常に「1」です。


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

Friends: 1

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

2 に答える 2

2

JSON オブジェクトがあります。文字列であり、PHP が で「カウント」できるものではありませんcount()。最初に JSON を解析する必要があります。

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

私がすぐにググったいくつかの参考文献:

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

于 2012-02-10T17:52:43.720 に答える
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}
于 2012-10-29T19:13:43.047 に答える