PHP如何实现评分
PHP实现评分功能的方法
使用数组和循环计算平均分
创建一个包含评分的数组,通过循环遍历数组计算总分和平均分。
$scores = [85, 90, 78, 92, 88];
$total = 0;
foreach ($scores as $score) {
$total += $score;
}
$average = $total / count($scores);
echo "平均分: " . $average;
使用表单接收用户评分
创建HTML表单接收用户输入的评分,PHP处理表单数据。

<form method="post" action="process_rating.php">
<input type="number" name="rating" min="1" max="5">
<button type="submit">提交评分</button>
</form>
// process_rating.php
$rating = $_POST['rating'];
// 验证评分范围
if ($rating >= 1 && $rating <= 5) {
// 存储或处理评分
echo "感谢您的评分: " . $rating;
} else {
echo "请输入1-5之间的有效评分";
}
数据库存储评分
将评分数据存储在MySQL数据库中,便于长期保存和分析。
// 连接数据库
$conn = new mysqli('localhost', 'username', 'password', 'database');
// 插入评分
$stmt = $conn->prepare("INSERT INTO ratings (score, user_id) VALUES (?, ?)");
$stmt->bind_param("ii", $score, $userId);
$stmt->execute();
加权评分计算

对不同评分项赋予不同权重进行计算。
$criteria = [
['score' => 80, 'weight' => 0.3],
['score' => 90, 'weight' => 0.5],
['score' => 70, 'weight' => 0.2]
];
$weightedScore = 0;
foreach ($criteria as $item) {
$weightedScore += $item['score'] * $item['weight'];
}
echo "加权评分: " . $weightedScore;
星级评分显示
将数值评分转换为可视化星级显示。
function renderStars($rating) {
$fullStars = floor($rating);
$halfStar = ($rating - $fullStars) >= 0.5;
$emptyStars = 5 - $fullStars - ($halfStar ? 1 : 0);
$output = str_repeat('★', $fullStars);
if ($halfStar) $output .= '½';
$output .= str_repeat('☆', $emptyStars);
return $output;
}
echo renderStars(3.5); // 输出: ★★★½☆☆






