3

我試圖做的是Facebook的朋友在PHP的計數器,所以代碼的結果會是這樣的:「你有1342點的朋友!」。Facebook好友計數器

因此,這是使用的代碼IM:

<?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['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...] 
+1

你必須json_decode()之前,指望它 – 2012-02-10 17:48:41

+0

http://stackoverflow.com/a/4066229/1100237 – coppettim 2012-02-10 17:54:56

回答

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對象,現在瞭解它...再次感謝! – Hawk 2012-02-10 19:05:01

0

你可以通過朋友容易FQL計數。

有反對,你可以查詢用戶表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}