我正在为我的每个用户存储一个分数。每个分数都应该映射到一个等级。例如,分数为 17 的人将被排名blogger
,因为blogger
其分数要求为 15。
$score = 17;
$rank = array(
15 => array('profile_rank_name' => 'Blogger', 'profile_rank_image' => 'blogger.png'),
18 => array('profile_rank_name' => 'News Editor', 'profile_rank_image' => 'news_editor.png'),
23 => array('profile_rank_name' => 'Researcher', 'profile_rank_image' => 'researcher.png'),
29 => array('profile_rank_name' => 'Publications Assistant', 'profile_rank_image' => 'publications_assistant.png'),
36 => array('profile_rank_name' => 'Editorial Assistant', 'profile_rank_image' => 'editorial_assistant.png'),
45 => array('profile_rank_name' => 'Copy Editor', 'profile_rank_image' => 'copy_editor.png'),
)
因为,在这种情况下,分数是 17,那么应该返回 $rank[15]。因为 $score 大于或等于 15。我该怎么做呢?
编辑:
Uksort 使用用户定义的比较函数按键对数组进行排序。我不确定它在内部是如何工作的。在下面的函数中,什么是 $a,什么是 $b?
if( ! function_exists('cmp'))
{
function cmp($a, $b)
{
return $a;
}
}
uksort($rank, "cmp");
编辑:我注意到我的问题含糊不清,我很抱歉,因为 iut 是凌晨 3 点,而且我没有像往常那样清楚地思考。谢谢大家的回复。我必须考虑重新表述这个问题。
接受的答案
public function get_profile_rank($score)
{
/* This method exists as an optimisation effort. Ranks are defined within the database table `author_profile_rank`.
* When we don't need application functionality on ranks and we only need to display the rank name and image we
* call this method. It saves using a table join to retrieve the rank name and image.
* http://stackoverflow.com/questions/19886351/returning-an-array-key-based-on-a-integer/19886467?noredirect=1#comment29583797_19886467
*/
if($score <= 17)
{
return array('profile_rank_name' => 'Blogger', 'profile_rank_image' => 'blogger.png');
}
elseif($score >= 45)
{
return array('profile_rank_name' => 'Copy Editor', 'profile_rank_image' => 'copy_editor.png');
}
$ranks = array(
23 => array('profile_rank_name' => 'Researcher', 'profile_rank_image' => 'researcher.png'),
29 => array('profile_rank_name' => 'Publications Assistant', 'profile_rank_image' => 'publications_assistant.png'),
36 => array('profile_rank_name' => 'Editorial Assistant', 'profile_rank_image' => 'editorial_assistant.png'),
);
$lower = function($val) use ($score)
{
if($val <= $score) return TRUE;
};
return $ranks[max(array_filter(array_keys($ranks), $lower))];
}