php实现打分器
实现基本打分功能
创建一个PHP函数接收分数参数并返回对应的评价等级。以下代码展示了如何根据分数范围返回不同等级:
function scoreEvaluator($score) {
if ($score >= 90) {
return '优秀';
} elseif ($score >= 80) {
return '良好';
} elseif ($score >= 70) {
return '中等';
} elseif ($score >= 60) {
return '及格';
} else {
return '不及格';
}
}
// 使用示例
echo scoreEvaluator(85); // 输出"良好"
数据库集成打分系统
当需要从数据库获取评分数据时,可以结合MySQL查询实现:
function getStudentScores($studentId) {
$conn = new mysqli('localhost', 'username', 'password', 'database');
$query = "SELECT score FROM student_scores WHERE student_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $studentId);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
return scoreEvaluator($row['score']);
}
return '无记录';
}
多维度评分计算
对于需要加权计算的评分系统,可以使用数组和权重因子:
function calculateWeightedScore($scores) {
$weights = [
'homework' => 0.3,
'exam' => 0.5,
'participation' => 0.2
];
$total = 0;
foreach ($scores as $key => $value) {
$total += $value * $weights[$key];
}
return round($total, 2);
}
// 使用示例
$studentScores = [
'homework' => 85,
'exam' => 90,
'participation' => 70
];
echo calculateWeightedScore($studentScores);
可视化评分展示
使用GD库生成评分图表:
function generateScoreChart($score, $maxScore = 100) {
$width = 300;
$height = 30;
$percentage = ($score / $maxScore) * 100;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 240, 240, 240);
$barColor = imagecolorallocate($image, 0, 150, 0);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);
imagefilledrectangle($image, 0, 0, ($width * $percentage / 100), $height, $barColor);
imagestring($image, 5, 10, 8, "得分: $score ($percentage%)", $textColor);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
}
// 调用生成图表
generateScoreChart(75);
表单评分提交处理
处理用户通过表单提交的评分:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$score = filter_input(INPUT_POST, 'score', FILTER_VALIDATE_INT);
if ($score !== false && $score >= 0 && $score <= 100) {
$evaluation = scoreEvaluator($score);
echo "您的评分结果: $evaluation";
} else {
echo "请输入0-100之间的有效分数";
}
}
对应的HTML表单:

<form method="post">
<label for="score">输入分数 (0-100):</label>
<input type="number" id="score" name="score" min="0" max="100" required>
<button type="submit">提交评分</button>
</form>






