我正在开发一款应用程序,可以为每个喜欢我页面的朋友奖励用户积分。
我需要一种方法来检查有多少用户的朋友喜欢我的网页。我开发了这段代码来检查每个朋友是否喜欢某个页面:
$friends = $facebook->api('/me/friends'); //list my friends
$time_start = microtime(true);
echo "<pre>";
$i = 0; //counter of likes
$b = 0; //counter of request in single batch API request
$batch_max = 50 // facebook allows max 50 requests in single batch API call
$page_id = '187941397895831'; //example page ID, i'm checking how many of my friends like this page
$batch = array(); //array used for creating batch API request
$data = array(); //array collecting all API requests results
foreach ($friends['data'] as $friend) {
$req = array(
'method' => 'GET',
'relative_url' => '/'.$friend['id'].'/likes'
);
$batch[] = json_encode($req);
$b++;
if ($b == 50) {
$params = array(
'batch' => '[' . implode(',',$batch) . ']'
);
$data[] = $facebook->api('/', 'POST', $params);
$b = 0;
$batch = array();
}
}
$params = array(
'batch' => '[' . implode(',',$batch) . ']'
);
$data[] = $facebook->api('/', 'POST', $params);
foreach ($data as $data_set) { //iterate through results of each api request
foreach ($data_set as $friend_likes) { //iterate through data of particular friend
$likes_array = json_decode($friend_likes['body'], true);
foreach ($likes_array['data'] as $single_like) { //iterate through all likes of a single friend
if ($single_like['id'] == $page_id) { //if page id found in user's likes increase counter
$i++;
}
}
}
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo $time."\n";
echo $i;
echo "</pre>";
exit;
在最终版本中,我不会检查我的朋友,而是检查每个用户的朋友。我的代码在14秒内执行,如果我不得不迭代,让我们说,100个用户它将是1400秒,这是可以长的。有没有更好的方法呢?我是facebook API的新手,所以我可能会错过一些明显的东西:)
答案 0 :(得分:0)
好的,这是代码的工作原理。您需要知道每个被检查用户的访问令牌。对于以前的代码,它在~0.6秒内执行而不是14秒。
$queryResults = array();
$facebook->setAccessToken($user->getAccessToken());
$fql = "SELECT '' FROM page_fan WHERE page_id = 'xxxxxxxxxxxx' AND uid IN (SELECT uid2 FROM friend WHERE uid1 = '".$user->getFbId()."')";
$fql = urlencode($fql);
try {
$queryResults = $facebook->api(
'/fql?q='.$fql
);
} catch (FacebookApiException $e) {
$log->setMessage(print_r($e,true));
$logMapper->save($log);
}
if (!empty($queryResults)) {
$user->setPoints(count($queryResults['data']));
$usersMapper->save($user);
}