1

我正在尝试将 Facebook 用户朋友的 FBID 存储在 mysql 数据库的列中。我已尝试查找有关此问题的其他答案,并且已尝试实现它(在 Laravel 4 中)。这是我所做的:

在 Facebook.php 文件中,提供者之一:

'friends'  => 'https://graph.facebook.com/me/friends?access_token='.$token->access_token

在我的 Oauth2 控制器中:

 $friends_list = $user['friends'];
 $friends_list_array  = json_decode($friends_list,true);
 $arr= $friends_list_array['data'];
 $friend_ids_arr = array();
 foreach($arr as $friend) {
   $friend_ids_arr[] = $friend['id'];
 }
 $friend_ids = implode("," , $friend_ids_arr); 

然后我想将 $friend_ids 对象存储在我数据库的“文本”列中。但是,在运行此程序时,我不断收到错误消息: Invalid argument supplied for foreach()

但很明显,它应该提供一个数组。有什么我没看到的吗?谢谢您的帮助。

4

1 回答 1

0

实际上返回的结果是 a json,返回的对象应该是这样的

{
    "id": "xxxxxxx", 
    "name": "Sheikh Heera", 
    "friends": {
        "data": [
            { "name": "RaseL KhaN", "id": "xxx" },
            { "name": "Yizel Herrera", "id": "xxx" }
        ], 
        "paging": {
        "next": "https://graph.facebook.com/xxx/friends?limit=..."
        }
    }
}

在你之后json_decode

$user = json_decode($user, true);

它应该看起来像

Array
(
    [id] => xxxxxxx
    [name] => Sheikh Heera
    [friends] => Array
    (
        [data] => Array
            (
                [0] => Array
                    (
                        [name] => RaseL KhaN
                        [id] => xxx
                    )

                [1] => Array
                    (
                        [name] => Yizel Herrera
                        [id] => xxx
                    )

            )

        [paging] => Array
            (
                [next] => https://graph.facebook.com/xxx/friends?limit=...
            )

    )

)

所以,现在你可以

 $friends_list = $user['friends'];
 $data = $friends_list['data'];

确保您的$data数组不为空,然后循环

if(count($data)) {
    $friend_ids_arr = array();
    foreach($data as $friend) {
        $friend_ids_arr[] = $friend['id'];
    }
}

因此,只有在其中有项目foreach时才会运行。$data

更新:它可能会帮助你

$url = "https://graph.facebook.com/me?fields=id,name,friends&access_token=YOUR_ACCESS_TOKEN";
$contents = json_decode(file_get_contents($url), true);
$friends = $contents['friends'];
$friend_ids_arr[]
foreach($friends['data'] as $friend)
{
    $friend_ids_arr[] = $friend['id'];
}
于 2013-07-06T02:30:28.523 回答