我想生成一个配对结构,我只有n(团队数量)和级别(n-1)
请看截图: 首先是四分之一决赛,每支队伍随机配对8支球队。
四分之一:
Austria->paired with = Hungary
Czech Republic->paired with = New Zealang
France->paired with = Belgium
Estonia->paired with = Iceland
使用PHP,您如何将团队随机配对,而不将其与自己的副本配对?
编辑:所有八个团队来自数据库。
答案 0 :(得分:2)
如果您有团队列表,则可以添加到基于零的数组。以下代码示例可以修改以满足您的要求。根据您的情况更改/修改它以动态获得团队并处理奇数/偶数团队计数。以下for循环仅适用于团队计数,所以其余部分适合您。
$teams[] = "Austria";
$teams[] = "Hungary";
$teams[] = "Czech Republic";
$teams[] = "New Zealang";
$teams[] = "France";
$teams[] = "Belgium";
$teams[] = "Estonia";
$teams[] = "Iceland";
$number_of_teams = count($teams);
// Shuffle the teams
shuffle($teams);// You get a shuffled array
// Pair the adjacent teams
for ( $index = 0; $index < $number_of_teams; $index +=2) {
// Pair $teams[$index ] with $teams[$index +1]
echo $teams[$index ] . "->paired with = " . $teams[$index+1] . "<br>";
}
答案 1 :(得分:0)
使用随机shuffle,而不是随机选择。将八个团队放入一个数组中并对阵列进行洗牌。这样你就可以保证没有重复,每个团队仍然只出现一次,但顺序不同。