使用 PHP 对 JSON 结果中的记录进行计数


Counting records in JSON result using PHP

大多数这些东西都是全新的,但基本上我在一个下雨的星期六中午玩弄Facebook API,以应对一些挑战。

我已获取本页底部的代码:-

http://developers.facebook.com/docs/reference/fql/

并稍微改变了一下。 基本上,我现在要做的只是在屏幕上打印朋友总数,我认为这就像返回 JSON 查询返回的记录数一样简单,但我无法正确处理。 我知道我做错了什么,但需要一个指针来说明什么。 目前我的代码只返回 1,它应该是 160 左右。

我的

代码在这里(我已经取出了我的应用程序ID/秘密):-

    <?php
  //Very basic code to pull out details about the logged in user.
  $app_id = 'myid';
  $app_secret = 'mysecret';
  $my_url = 'http://lab.2toria.com/facebook/test1.php';
  $code = $_REQUEST["code"];
 //auth user
 if(empty($code)) {
    $dialog_url = 'https://www.facebook.com/dialog/oauth?client_id=' 
    . $app_id . '&redirect_uri=' . urlencode($my_url) ;
    echo("<script>top.location.href='" . $dialog_url . "'</script>");
  }
  //get user access_token
  $token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
    . $app_id . '&redirect_uri=' . urlencode($my_url) 
    . '&client_secret=' . $app_secret 
    . '&code=' . $code;
  $access_token = file_get_contents($token_url);
  // Run fql query
  $fql_query_url = 'https://graph.facebook.com/'
    . '/fql?q=SELECT+uid2+FROM+friend+WHERE+uid1=me()'
    . '&' . $access_token;
  $fql_query_result = file_get_contents($fql_query_url);
  $fql_query_obj = json_decode($fql_query_result, true);
  //Now need to find a way to count the number of results returned in the array to get the number of facebook friends.
  for($a=0;$a<count($fql_query_obj);$a++)
  {
    $theCount++;  
  }
  echo '<pre>';
  print_r("Number of friends:");
  print_r($theCount);
  echo '</pre>';

?>

提前谢谢。席

你应该这样做

for($a=0;$a<count($fql_query_obj['data']);$a++)>

因为Facebook响应将具有包含原始数据的数据属性。

不确定,但是您不能打印count($fql_query_obj),因为它现在是一个数组,这应该返回相同的值,不是吗?

编辑:你有没有检查过Facebook是否给你一个有效的json_object?