Home > other >  PHP/MYSQL compare/contrast values of an array (soccer tournament schedule)
PHP/MYSQL compare/contrast values of an array (soccer tournament schedule)

Time:07-12

I'm trying to create a soccer tournament schedule. The problem with this is, that I don't know how to compare or contrast the values ​​in an array. Within an array, every value should be compared to every other value except its own. For example, there are these teams: Team1, Team2, Team3, Team4.

Now the Code should generate the following:

Team1 - Team2 
Team3 - Team4 
Team2 - Team3 
Team1 - Team4 
Team2 - Team4 
Team1 - Team3 

It is important, that each team plays against all other teams, but if possible not one after the other. I don't need something like this:

Team1 - Team2 
Team1 - Team3 
Team1 - Team4 
...and so on

Further, it should also work with an odd number of teams.

Another easy example:

Array:

$teams('Team1', 'Team2', 'Team3', 'Team4');

Output:

|Team A | Against | Team B |
|:----- |:------: |-------:|
|Team1  |    -    |Team2   |
|Team3  |    -    |Team4   |
|Team2  |    -    |Team3   |
|Team1  |    -    |Team4   |
... an so on

I would be glad about an answer, thanks.

CodePudding user response:

Something like this?

$teams = ['team1', 'team2', 'team3', 'team4', 'team5'];

for( $i = 0; $i<count($teams)-1; $i  ) {
    for( $j=$i; $j<count($teams); $j  ) {
        if ( $i == $j ){ continue; } #cannot play with yourself
        echo $teams[$i] . ' Plays ' . $teams[$j] . PHP_EOL;
    }
}

RESULT

team1 Plays team2
team1 Plays team3
team1 Plays team4
team1 Plays team5
team2 Plays team3
team2 Plays team4
team2 Plays team5
team3 Plays team4
team3 Plays team5
team4 Plays team5

CodePudding user response:

This should be a good starting point...

<?php

$teams = ['Team 1', 'Team 2', 'Team 3', 'Team 4'];
$games = [];

for ($index = 0, $indexMax = count($teams); $index < $indexMax; $index  ) {
    foreach ($teams as $indexT => $team) {
        if ($indexT === $index) {
            continue;
        }
        $games[] = [$teams[$index] => $team];
    }
}

shuffle($games);
  • Related