What we are going to do, is split the players in 2 groups: contenders 1 & contenders 2. We're going to fill contenders a with consecutive players of the same school:
If we name the schools a single letter for brevity, what we'll essentially have is:
A A A A B B B C
C C D D E E F F
Or, if we flip it, it becomes clearer:
A C
A C
A D
A D
B E
B E
B F
C F
What happens if one school has > the half of the total number of players? Well, let's see:
A A A A A
A B B C D
So:
A A <= one A vs. A, which is unavoidable, but the method still works.
A B
A B
A C
A D
I cheated a bit here: I sorted out the players from the biggest school first. It however still works as long as we group schools together. Let's take my output of $a = range('A','F'); shuffle($a):, which here resulted in: FCADBE, which gives us:
F A
F D
C D
C B
C B
A B
A E
A E
.. which works, also for A > half:
C A
A A <= that one double again, unavoidable
A D
A B
A B
Let's break this into parts. What we have to do is:
- sort the players by school
- break this sorted array into 2 groups.
- create pairs by adding on from the first group & one from the second group, in order.
The advantage of cutting it down is so you can find answers:
- hundreds of questions on SO
- this is a nice answer
- We could use a MultiIterator, which would be a logical (and working) choice, but I'll show you another short way of creating pairs of 2 arrays (or triplets if you have 3 arrays, etc.)
So, let's do that:
//sort by school
$players = ... your array ...
usort($players,function($playerA, $playerB){
return strcmp($playerA['school'], $playerB['school']);
});
//voila, sorted
//break this into 2 groups:
$size = ceil(count($players) / 2); // round UP
$groupA = array_slice($players,0,$size);
$groupB = array_slice($players,$size);
//create our duels array:
$duels = array_map(null, $groupA, $groupB);
$duels now has this content with your input:
[
[
{
"name": "juan",
"school": "ABC"
},
{
"name": "arnold",
"school": "DEF"
}
],
[
{
"name": "leo",
"school": "ABC"
},
{
"name": "ash",
"school": "ECD"
}
],
[
{
"name": "simon",
"school": "DEF"
},
{
"name": "luke",
"school": "ECD"
}
]
]