gpt4 book ai didi

php - 合并来自两个不同数据集的数据(Facebook 和 MySQL)

转载 作者:可可西里 更新时间:2023-11-01 07:55:16 26 4
gpt4 key购买 nike

我想知道这是否是解决此问题的最佳方法。我正在将 Facebook 用户 friend 数据(来自 facebook - 返回一个多数组)与该列表中投票的用户的投票(来自 MySQL)合并。

我就是这样完成的。我是一名初级开发人员,正在寻求帮助以尽可能优化我的代码。

public function getFriendVotes(){
global $facebook;

// Get The users friends that use this app from facebook
$friends = $facebook->api_client->fql_query(
"SELECT uid, first_name, last_name
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=$this->user)"
);

// Create an array of just the ids
foreach($friends as $friend){
$userids[] = $friend['uid'];
}

// Create a string of these ids
$idstring = implode(",", $userids);

// Get the votes from only the users in that list that voted
$result = $this->db->query(
"SELECT vote, userid FROM user_votes WHERE userid IN ($idstring)"
);

// Create a new result set (multi array). Include the data from the first
// Facebook query, but include only those who voted and append their votes
// to the data
$row = $result->fetch_assoc();
foreach($friends as $friend){
if($row['userid'] == $friend['uid']){
$return[$count] = $friend;
$return[$count]['vote'] = $row['vote'];
$row = $result->fetch_assoc();
$count++;
}
}
return $return;
}

最佳答案

我假设 fql_query 确实支持 mysql 语法,使用 LEFT JOIN 代替创建额外查询会更有效,这是我的代码版本:

public function getFriendVotes(){
global $facebook;

// Get The users friends that use this app from facebook
$friends = $facebook->api_client->fql_query("
SELECT DISTINCT u.uid,u.first_name,u.last_name
FROM user AS u
LEFT JOIN friend AS f ON uid=uid2
WHERE f.uid1='{$this->user}'
");
$arrayUsers = array();
// Create an array of just the ids
foreach($friends as $v){
$arrayUsers[$friend['uid']] = $v;
}
unset($friends);

// Create a string of these ids
$idstring = implode(",", array_keys($arrayUsers));

// Get the votes from only the users in that list that voted
$result = $this->db->query(
"SELECT vote, userid FROM user_votes WHERE userid IN ({$idstring})"
);

$result = array();
// Create a new result set (multi array). Include the data from the first
// Facebook query, but include only those who voted and append their votes
// to the data
while($v = $result->fetch_assoc())
{
if(isset($arrayUsers[$v['userid']])
{

$arrayUsers[$v['userid']] = $v['vote'];

$result[] = $arrayUsers[$v['userid']];

unset($arrayUsers[$v['userid']], $v);
}
}

return $return;
}

关于php - 合并来自两个不同数据集的数据(Facebook 和 MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1704137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com