php实现排名
PHP实现排名的方法
使用数组排序实现排名
通过PHP内置的排序函数对数组进行排序,然后根据排序结果生成排名。
$scores = [85, 92, 78, 96, 88];
arsort($scores); // 降序排序
$rank = 1;
foreach ($scores as $index => $score) {
echo "排名{$rank}: 分数{$score}<br>";
$rank++;
}
数据库查询实现排名
在MySQL等数据库中,可以使用窗口函数或变量实现排名查询。

-- MySQL 8.0+ 使用RANK()函数
SELECT
name,
score,
RANK() OVER (ORDER BY score DESC) as rank
FROM students;
PHP中执行该查询并输出结果:

$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$stmt = $pdo->query("SELECT name, score, RANK() OVER (ORDER BY score DESC) as rank FROM students");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo "姓名: {$row['name']}, 分数: {$row['score']}, 排名: {$row['rank']}<br>";
}
处理并列排名的情况
当多个项目分数相同时,应该给予相同排名,并跳过后续名次。
$scores = [90, 85, 90, 80, 75];
arsort($scores);
$prevScore = null;
$rank = 0;
$skip = 0;
foreach ($scores as $index => $score) {
if ($score !== $prevScore) {
$rank += 1 + $skip;
$skip = 0;
} else {
$skip++;
}
echo "排名{$rank}: 分数{$score}<br>";
$prevScore = $score;
}
分组排名实现
当需要按不同组别分别排名时,可以使用多维数组或数据库分组查询。
$students = [
['name' => '张三', 'group' => 'A', 'score' => 85],
['name' => '李四', 'group' => 'B', 'score' => 90],
// 更多数据...
];
// 按组别分组
$grouped = [];
foreach ($students as $student) {
$grouped[$student['group']][] = $student;
}
// 对各组单独排名
foreach ($grouped as $group => $members) {
usort($members, function($a, $b) {
return $b['score'] - $a['score'];
});
echo "<h3>组别 {$group} 排名</h3>";
$rank = 1;
foreach ($members as $member) {
echo "排名{$rank}: {$member['name']} ({$member['score']}分)<br>";
$rank++;
}
}






