PHP实现根据一个值计算出对应等级 原创

使用PHP实现根据一个分数获取分数等级[二分]

function getGradeScore(int|float $score, array $grades) {
	$gradeNum = count($grades);
	if ($gradeNum === 0) return 0;
	if ($gradeNum === 1) return $score > reset($grades) ? reset($grades) : 0;
	
	$middleIndex = floor(count($grades) / 2);
	$left = array_slice($grades, 0, $middleIndex);
	$right = array_slice($grades, $middleIndex);
	$endLeft = end($left);
	$firstRight = reset($right);
	
	if ($score >= $endLeft && $score < $firstRight) return $endLeft;
	if ($score === $firstRight) return $firstRight;
	
	if ($score < $endLeft) return getGradeScore($score, $left);
	
	return getGradeScore($score, $right);
}
$grades = [100 => 1, 200 => 2, 300 => 3, 500 => 4, 800 => 5, 1200 => 6, 1700 => 7, 2500 => 8, 3000 => 9, 3500 => 10, 4500 => 11, 6000 => 12, 8000 => 13, 10000 => 14, 13000 => 15, 17000 => 16, 22000 => 17, 30000 => 18];
$score = rand(0, 3000);

$gradeScore = getGradeScore($score, array_keys($grades));
echo '分数:' . $score;
echo '等级:' . ($grades[$gradeScore] ?? 0);

$grades2 = [1 => 100, 2 => 200, 3 => 300, 4 => 500, 5 => 800, 6 => 1200, 7 => 1700, 8 => 2500, 9 => 3000, 10 => 3500, 11 => 4500, 12 => 6000, 13 => 8000, 14 => 10000, 15 => 13000, 16 => 17000, 17 => 22000, 18 => 30000];
$score = rand(0, 50000);
$gradeScore2 = getGradeScore($score, array_values($grades2));
echo '分数:' . $score;
echo '等级:' . ((int) array_search($gradeScore2, $grades2));
posted @ 2023-09-12 08:59  mailfor  阅读(0)  评论(0编辑  收藏  举报  来源