$q = "SELECT user_id FROM users WHERE partner='$qpartner' AND group_id='$gi' AND status='1'";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
while ($row = mysqli_fetch_array($r)) {
$usinneed[] = $row[0];
}
$affected = mysqli_affected_rows($dbc);
$q2 = "SELECT user_id FROM users WHERE partner<>'$qpartner' AND group_id='$gi' AND status='1' ORDER BY RAND() LIMIT $affected";
$r2 = mysqli_query ($dbc, $q2) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
while ($row = mysqli_fetch_array($r2)) {
$potent_partners[] = $row[0];
}
$current = end($usinneed);
$partners = array();
foreach ($usinneed as $user)
{
$partners[$user] = $current;
$current = $user;
$q = "UPDATE users SET partner = '{$partners[$user]}' WHERE user_id = '{$user}'";
mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
}
print_r($partners);
一旦我来到$ current,我就迷失了;这就是需要改变的地方,我需要帮助
$ usinneed是需要合作伙伴的所有用户的数组,$ potent_partners是一系列潜在的合作伙伴,可以与有用的用户配对($ usinneed)。答案 0 :(得分:1)
array_combine可能会有任何帮助吗?
修改强>
鉴于下面的评论,这里是新的细节(格式正确):
我们从填充两个数组的查询开始:$usersInNeed
(那些没有合作伙伴的数组)和$newPartners
(需要配对的人数组)与$usersInNeed
)
我们使用array_combine在PHP中将它们配对。所以
$usersInNeed = Array(2,4); // Keys
$newPartners = Array(8,5); // values
$combined = array_combine($usersInNeed,$newPartners); // result: Array(2 => 8, 4 => 5);
现在,我们返回数据库并与合作伙伴一起更新这些用户。你可以做很多方法,但是foreach似乎最简单:
// take each entry in $combined and break it out so the key is "$userInNeed" and the
// value is "$newPartner" (illustrate what array_combine did)
foreach ($combined as $userInNeed => $newPartner)
{
$sql = "UPDATE users SET partner='{$newPartner}' WHERE user_id='{$userInNeed}';";
// execute the statement
}
答案 1 :(得分:0)
你喜欢这样:
foreach($ usinneed as $ user) { foreach($ potent_partners作为$ partner) { 你的sql代码里面 现在你有$合作伙伴[$ user] }
}
答案 2 :(得分:0)
没有经过测试,但也许你可以这样做。
$query = 'UPDATE users SET users.partner = (SELECT partners.user_id FROM users AS partners WHERE partners.user_id != users.user_id ORDER BY RAND() LIMIT 1) WHERE 1';
是否允许两个不同的用户拥有相同的合作伙伴? 每个用户的合作伙伴是否还必须将该用户作为其合作伙伴? 如果没有足够的合作伙伴,会发生什么?用户?