我正在开发一个应用程序,该应用程序将为喜欢我页面的每个朋友奖励其用户积分。
我需要一种方法来检查有多少用户的朋友喜欢我的页面。我开发了这段代码来检查我的每个朋友是否喜欢特定的页面:
$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 的新手,所以我可能会错过一些明显的东西 :)