这是我的代码:
$totalRounds = 1;
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4', 'Team 5');
echo 'Total Teams: ' , $totalTeams = count($teams) , '<br/>';
$turns = $totalTeams;
for($round=1; $round<$totalRounds+1; $round++){
echo 'Round: ' , $round , '<br/>';
for($homeTeam=0; $homeTeam<$totalTeams-1; $homeTeam++){
for($awayTeam=0; $awayTeam<$totalTeams; $awayTeam++){
if($teams[$homeTeam] != $teams[$awayTeam]){
echo $teams[$homeTeam] , ' v/s ' , $teams[$awayTeam] , '<br/>';
}
}
unset($teams[$homeTeam]);
}
echo '<br/>';
}
我的预期输出是:
Team 1 v/s Team 2 <br/>
Team 1 v/s Team 3 <br/>
Team 1 v/s Team 4 <br/>
Team 1 v/s Team 5 <br/>
Team 2 v/s Team 3 <br/>
Team 2 v/s Team 4 <br/>
Team 2 v/s Team 5 <br/>
Team 3 v/s Team 4 <br/>
Team 3 v/s Team 5 <br/>
Team 4 v/s Team 5 <br/>
我的实际输出给出了未定义的索引错误
一旦修复,我不知道如何分配主队和客队。例如。第1队应该只有2场主场比赛,而不是4场比赛。每支队伍将参加2场主场比赛和2场客场比赛。
答案 0 :(得分:1)
你的代码正在摧毁阵列,例如:
first iteration: $home = 0; $away = 0
end of iteration: delete teams[0]
second iteration, $home = 1; $away = 0 - OOPS, teams[0] no longer exists
而不是在你去的时候取消设置数组,你应该将内循环基于外循环,例如:
for($home = 0; ...) {
for($away = $home + 1; ...) {
答案 1 :(得分:1)
您可以使用以下
修复代码$totalRounds = 1;
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4', 'Team 5');
echo 'Total Teams: ' , $totalTeams = count($teams) , '<br/>';
$turns = $totalTeams;
for($round=1; $round<$totalRounds+1; $round++){
echo 'Round: ' , $round , '<br/>';
for($homeTeam = 0; $homeTeam < $totalTeams - 1; $homeTeam++) {
for($awayTeam=$homeTeam + 1; $awayTeam < $totalTeams; $awayTeam++) {
echo $teams[$homeTeam] , ' v/s ' , $teams[$awayTeam] , '<br/>';
}
}
echo '<br/>';
}