我允许用户在我的网站上注册“游戏”;正常情况下,他们都会收到唯一的ID。在给定的时间点,注册将停止。那时,我想运行代码来分配合作伙伴,但不是配对。
所以,如果我有以下内容:
+ -------- + ------- +
| user_id |伙伴|
+ -------- + ------- +
|
1 |
|
|
3 |
|
|
7 |
|
|
11 |
|
|
12 |
|
|
18 |
|
+ -------- + ------- +
我该怎样做才能得到这样的结果:
+ -------- + -------- +
| user_id | partnr |
+ -------- + -------- +
|
1 |
7 |
|
3 |
12 |
|
7 |
18 |
|
11 |
1 |
|
12 |
11 |
|
18 |
3 |
+ -------- + -------- +
1,7,18,3,12,11; 1,7,18,3,12,11
$query = "SELECT users FROM tabl";
$result = mysql_query ($query)
or die ("Query '$query' failed with error message: \"" . mysql_error () . '"');
while ($row = mysql_fetch_array($result)) {
$users[] = $row[0];
}
$current = end($users);
$partners = array();
foreach ($users as $user)
{
$partners[$user] = $current;
$current = $user;
}
print_r($partners);
感谢Sjoerd,这似乎有效,但我需要将其写回合作伙伴专栏。
答案 0 :(得分:5)
循环遍历数组并分配合作伙伴的代码:
$users = array('john', 'jack', 'jones', 'joelle', 'jesica');
$current = end($users);
$partners = array();
foreach ($users as $user)
{
$partners[$user] = $current;
$current = $user;
}
print_r($partners);
答案 1 :(得分:1)
将表更新为user_id,partner_id对
$results = mysql_query("SELECT user_ids FROM -tablename- ORDER BY RAND()");
$user_ids = array();
$partner_ids = array();
while($row = mysql_fetch_array($results))
{
$user_ids[] = $row['user_id'];
$partner_ids[] = $rowp['user_id'];
}
$lastPartnerId = array_pop($partner_ids);
array_unshift($partner_ids,$lastPartnerId);
for($i=0;$i<count($user_ids);$i++)
{
mysql_query("UPDATE -tablename- SET partner_id = {$partner_ids[$i]} WHERE user_id = {$user_ids[$i]}");
}
答案 2 :(得分:0)
对不起,如果有错误......我很久没有编写PHP代码......
$i = rand(1, length($players) - 1)
for ($p = 0; $p < length($players); $p++)
{
$partners[$p] = $players[$i];
if (++$i > length($players))
{
$i = 0;
}
}