0

PHPを使用してFacebookユーザーの友達リストをMySQLに保存する方法は?

以下の PHP コードを使用して、ユーザーの友達リストを取得して印刷できますか?

//get friends list
$friends_list = file_get_contents('https://graph.facebook.com/me/friends?access_token=' . $atoken );

$friends_list_array  = json_decode($friends_list,true); 

//convert so that store in mysql 
$my_friends = implode("," , $friends_list_array['data']);
    echo "</br> my friends" . $my_friends;

//result my friendsArray,Array,Array,Array,Array,Array,Array,Array.....

友達リストを MySQL に保存するにはどうすればよいですか?

4

3 に答える 3

3

friends接続は友人のを返し、name配列にカプセル化idされます。dataしたがって、配列を1つ下に移動して、前にIDを収集する必要がありますimplode

$friends_list = file_get_contents('https://graph.facebook.com/me/friends?access_token=' . $atoken );
$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);
echo $friend_ids; // output: id1,id2,id3...etc
于 2012-05-27T17:05:50.670 に答える
0

var_dump($friends_list_array)実際に作業しているものを確認できるように、 aから始めます。次に、必要な関連データを取得してデータベースに挿入するループを作成します。

次のようなもの:

get the data
decode the data
create an empty array "arr"
foreach data as row
    do something with row, output should be something like
    "(123, 'John Smith', .....)"
    add this value to "arr"
implode "arr" with ","
add the start of the query ("insert into... ...values")
run the query.

ただし、これはおそらく避けるのが最善です。人々の友人は常に変化し、同意しない限りデータを保存することを望まない場合があります。

于 2012-05-27T15:15:39.093 に答える
0

以下を試してみてください。以下はテストしていません。

$sql_string = "insert into friends_table(friend_id,friend_name) values";
$insertValues = array();
$friends_list_array = json_decode(....)['data'];
foreach($friends_list_array as $friends){
    $insertValues[] = "({$friend['id']}, {$friend['name']})";
}
if (mysql_query($sql_string . implode(",", $insertValues) . ";")){
    //added all the data..
}else{
    //some error..
} 

PS: Kolink によって指摘された問題は非常に有効です。あなたがしていることには、別の方法があるかもしれません。


更新

フレンドのすべての ID を1 つのフィールドに格納する必要がある場合(これは実際には悪い考えです。以下を参照してください)、JSON を使用してフレンド リスト データをシリアル化し (可能性があります)、それをストリング。

$friends_list_array = json_decode(....)['data'];
$friends_id = array_map(function($friend){ return $friend['id'];},$friends_list_array);
$friends_list_json = json_encode($friends_id);
if (mysql_query("insert into friends_table(user, friends) values ('$curUserId','$friends_list_json';")){
    //added all the data..
}else{
    //some error..
} 

リスト全体に一度にアクセス/変更しない限り、シリアル化されたデータを単一のフィールドに格納することは実際には悪い考えです。より良いオプションは、データを行全体に分散させることです。

于 2012-05-27T15:25:20.213 に答える