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

77 Views Asked by At

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.

1

There are 1 best solutions below

1
Guido Faecke On

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);