如何用PHP随机化一个Facebook好友?

时间:2011-02-09 15:13:33

标签: php facebook random

我正在尝试从我的火葬名单中随机化一位Facebook好友。

因为我是PHP的新手,有人可以帮助我,让我知道怎么做吗?

$friends_json = file_get_contents('https://graph.facebook.com/me/friends?access_token='.$session["access_token"]);
$friends = json_decode($friends_json, true);
$friend_rand = array_rand($friends, 1); // <-- is that right? how can I print it on screen?

3 个答案:

答案 0 :(得分:2)

array_rand返回一个键数组。由于您只提取一个元素,因此要打印的代码是

echo($friend_rand[0]);

Andrea的答案也有效,但是会打印数组(而不是元素)。

答案 1 :(得分:1)

随机化整个朋友群是浪费代码和处理,只需从数组中提取一个随机名称。

只需从数组中选择一个随机密钥即可。而不是你的最后一行,使用:

echo $friends[mt_rand(0, count($friends)-1)];

答案 2 :(得分:0)

好的,你的代码几乎正确,问题是返回的结果包含在“data”数组中,所以你需要这样做:

$friends_json = file_get_contents('https://graph.facebook.com/me/friends?access_token='.$session["access_token"]);
$friends = json_decode($friends_json, true);
$k = array_rand($friends["data"]);
echo $friends["data"][$k]["name"];

或者最后两行可以替换为:

echo $friends["data"][array_rand($friends["data"])]["name"];