Make a ranking of students' scores. The scores are an array. After ranking, the ranking results are output:
For example, $scores = array(90,100,100)
; Custom function implementation returns array $rank(3,1,1)
;
过去多啦不再A梦2017-05-16 13:18:24
<?php
$arr = [99,100,100];
$arr1=$arr;
rsort($arr1);
$c=[];
foreach ( $arr as $v){
$b= array_search($v, $arr1);
$c[]=$b+1;
}
print_r($c);
?>
This can meet your needs, but I have a question. The two are tied for first place. Shouldn’t the one who got 99 in the exam be the second place?
ringa_lee2017-05-16 13:18:24
What the questioner wants is to display the rankings in the order of the original array (can be tied). The general idea is to supplement the original array with position information, and then reversely construct the ranking array based on the sorted results. It’s a bit long to write out:
get_ranks(a[1:n])
s ← array(n)
ranks ← array(n)
for i from 1 to n ▷ s[i] has record type
s[i] ← {position: i, value: a[i], rank: 0}
descending_sort(s by value) ▷ sort by s[i].value
s[1].rank ← 1
for i from 2 to n
if s[i].value < s[i-1].value ▷ dense rank
s[i].rank ← s[i-1].rank + 1
else
s[i].rank ← s[i-1].rank
for i from 1 to n ▷ construct result
ranks[s[i].position] ← s[i].rank
return ranks[]
Note that if there are multiple nth people tied for the nth place, the next person will be the n+1th person, which is a bit different from the example given by the questioner. The complexity bottleneck of the entire algorithm is sorting, which is O(n lgn).
phpcn_u15822017-05-16 13:18:24
http://www.php.net/manual/zh/...
The built-in data sorting should be able to solve your problem
我想大声告诉你2017-05-16 13:18:24
First sort this array by score, and then revsert this array. Then just get the key according to the score.
In addition: your scores are not written in the database, so they are taken out in order