这是一个有效的解决方案。如果您需要更好地解释它的工作原理,请告诉我。我已将调试语句留在其中,因此您应该能够辨别它在做什么。该解决方案适用于任意数量的竞争者,只要它们$num_elements
在每个数组中都相同。
$result = array();
$result['a'] = array(1, 3, 4, 5);
$result['b'] = array(1, 2, 3, 7);
$result['c'] = array(2, 3, 3, 5);
$num_elements = 4; // In each array
$num_competitors = count( $result);
$finish_order = array();
$keys = $winners = array_keys( $result);
// $i is the current index into each competitor's array
// $j is the current index into the $keys array (telling us the current competitor)
// $k is the next index into the $keys array (telling us the next competitor, i.e. the competitor to compare the current competitor with)
for( $i = 0; $i < $num_elements; $i++) {
// If we've eliminated all but one winner, we're done!
if( count( $winners) == 1) {
$finish_order[] = array_pop( $winners);
break;
}
echo 'Element number ' . $i . "\n";
for( $j = 0; $j < $num_competitors; $j++) {
// If we've already eliminated this competitor, continue;
if( !isset( $winners[$j])) continue;
for( $k = $j + 1; $k < $num_competitors; $k++) {
// If we've already eliminated this competitor, continue;
if( !isset( $winners[$k])) continue;
echo "\t - Who wins: " . $result[ $keys[$j] ][$i] . ' from ' . $keys[$j] . ' or ' . $result[ $keys[$k] ][$i] . ' from ' . $keys[$k] . "?\n";
if( $result[ $keys[$j] ][$i] < $result[ $keys[$k] ][$i]) {
echo "\t\t *** " . $keys[$k] . ' is out!' . "\n";
$finish_order[] = $keys[$k];
unset( $winners[$k]);
}
if( $result[ $keys[$j] ][$i] > $result[ $keys[$k] ][$i]) {
echo "\t\t *** " . $keys[$j] . ' is out!' . "\n";
$finish_order[] = $keys[$j];
unset( $winners[$j]);
}
}
}
}
echo "Game over - Result order is: " . implode( ', ', array_reverse( $finish_order));
输出:
Element number 0
- Who wins: 1 from a or 1 from b?
- Who wins: 1 from a or 2 from c?
*** c is out!
Element number 1
- Who wins: 3 from a or 2 from b?
*** a is out!
Game over - Result order is: b, a, c
演示