php实现单淘汰赛制
单淘汰赛制简介
单淘汰赛制是一种竞赛形式,参赛者每轮两两对决,胜者晋级,败者淘汰,直到决出冠军。常见于体育赛事、游戏比赛等场景。
数据结构设计
使用数组或数据库表存储参赛者信息。示例数据结构:

$participants = ['选手A', '选手B', '选手C', '选手D']; // 参赛者列表
$matches = []; // 存储每轮对阵信息
生成对阵表
通过随机或指定规则配对参赛者,确保每轮人数为2的幂次方(不足时可轮空)。

function generateMatches(array $participants): array {
shuffle($participants); // 随机打乱顺序
$matches = [];
for ($i = 0; $i < count($participants); $i += 2) {
$matches[] = [$participants[$i], $participants[$i + 1] ?? '轮空'];
}
return $matches;
}
模拟比赛过程
逐轮处理对阵表,假设通过函数simulateMatch决定胜负(可替换为实际逻辑):
function simulateMatch($player1, $player2): string {
return rand(0, 1) ? $player1 : $player2; // 随机返回胜者
}
function runTournament(array $participants): string {
while (count($participants) > 1) {
$winners = [];
$matches = generateMatches($participants);
foreach ($matches as $match) {
$winner = simulateMatch($match[0], $match[1]);
$winners[] = $winner;
}
$participants = $winners;
}
return $participants[0]; // 返回冠军
}
处理轮空情况
若参赛者数量非2的幂次方,首轮需处理轮空:
function handleBye(array &$participants): void {
$count = count($participants);
if (($count & ($count - 1)) !== 0) { // 判断是否为2的幂次方
$byes = 2 ceil(log($count, 2)) - $count;
$participants = array_merge($participants, array_fill(0, $byes, '轮空'));
}
}
完整调用示例
$participants = ['选手A', '选手B', '选手C', '选手D', '选手E'];
handleBye($participants); // 处理轮空
$champion = runTournament($participants);
echo "冠军是: " . $champion;
扩展建议
- 持久化存储:使用数据库记录每轮结果,便于复盘或统计。
- 胜负逻辑:根据实际需求替换
simulateMatch,如积分计算或用户输入。 - 可视化输出:生成树状图或表格展示比赛进程。
通过上述方法可实现基础的单淘汰赛制,逻辑清晰且易于扩展。






