问题
I need rank in my system. I have an array $arr = array(120,26,38,96,22);
. I need to rank the index inside without changing their position.
The output I need is something like:
120 is rank 1, 26 is rank 4, 38 is rank 3, 96 is rank 2, 22 is rank 5
I've tried this, but all ranked as rank 1:
<?php
$arr = array(120,26,38,96,22);
$rank = 0;
$score=false;
$rows = 0;
foreach($arr as $sort){
$rows++;
if($score != $arr){
$score = $arr;
$rank = $rows;
}echo $sort.' is rank '.$rank.'</br>';
}
?>
And also I need the array length to be dynamic.
回答1:
Here's one way:
$arr = array(120,26,38,96,22);
$rank = $arr;
rsort($rank);
foreach($arr as $sort) {
echo $sort. ' is rank ' . (array_search($sort, $rank) + 1) . '</br>';
}
- Copy the original array as
$rank
and sort in reverse so the keys will be the rank -1 - Loop the original array and search for that value in
$rank
returning the key (rank) - Add 1 since keys start at 0
Or another possibility:
$arr = array(120,26,38,96,22);
$rank = $arr;
rsort($rank);
$rank = array_flip($rank);
foreach($arr as $sort) {
echo $sort . ' is rank '. ($rank[$sort] + 1) . '</br>';
}
- Copy the original array as
$rank
and sort in reverse so the keys will be the rank -1 - Flip the
$rank
array to get values as keys and rank as values - Loop the original array and use the value as the
$rank
key to get the rank - Add 1 since keys start at 0
回答2:
Do it like this:
$arr=array(120,26,38,96,22);
//get a copy adn use original for original order
$result=$arr;
//sort it numeric and reverse
rsort($result,SORT_NUMERIC);
//create the result
$result = array_map(function($a){return $a+1;},array_flip($result));
//print it
print_r($result);
Result:
Array ( [120] => 1 [96] => 2 [38] => 3 [26] => 4 [22] => 5 )
Get original order:
$resultxt = array();
foreach($arr as $sort){
$resulttxt[] = $sort.' is rank '.$result[$sort];
}
print implode(', ',$resulttxt).'<br>';
array_map http://php.net/manual/en/function.array-map.php
array_flip http://php.net/manual/en/function.array-flip.php
来源:https://stackoverflow.com/questions/41617333/how-to-rank-arrays-index-in-php