我这里有一个使用Facebook API的PHP页面。
我正在尝试做的是(在用户设置权限后),通过以下方式获取用户朋友的用户ID:$facebook->api('/me/friends')
。问题是,我只想随机获得10个朋友。我可以轻松地通过使用 /me/friends?limit=10
将结果限制为 10 个,但话又说回来,这不是随机的。
所以这就是我现在所拥有的:
$friendsLists = $facebook->api('/me/friends');
function getFriends($friendsLists){
foreach ($friendsLists as $friends) {
foreach ($friends as $friend) {
// do something with the friend, but you only have id and name
$id = $friend['id'];
$name = $friend['name'];
shuffle($id);
return "@[".$id.":0],";
}
}
}
$friendsies = getFriends($friendsLists);
$message = 'I found this Cover at <3 '.$Link.'
'.$friendsies.' check it out! :)';
我已经尝试了shuffle(),以及这里的第一个选项:https://stackoverflow.com/a/1656983/1399030,但我认为我可能做错了什么,因为它们不返回任何内容。我很确定我已经接近了,但到目前为止我尝试的都没有奏效。能做到吗?
您需要
在foreach之前使用shuffle,以便实际洗牌数组。
之后,您需要限制为 10 位朋友。我建议添加一个 $i var 以计数到 10,并添加到一个新数组中。
像这样:
function getFriends($friendsLists){
$formatted_friends = array();
$i = 0;
foreach ($friendsLists as $friends) {
// I'm guessing we'll need to shuffle here, but might also be before the previous foreach
shuffle($friends);
foreach ($friends as $friend) {
// do something with the friend, but you only have id and name
// add friend as one of the ten
$formatted_friends[$i] = $friend;
// keep track of the count
$i++;
// once we hit 10 friends, return the result in an array
if ($i == 10){ return $formatted_friends; }
}
}
}
但请记住,它将返回一个数组,而不是您可以在 echo 中使用的字符串。如果需要,可以将其放在回显中以进行调试:
echo 'friends: '.print_r($friendsies, true);