Reputation: 2708
I have an array i.e.
Array
(
[18] => 0.6667
[228] => 0.3333
[25] => 0.3333
[568] => 0.3333
[762] => 0
[740] => 0
[742] => 0
)
I want to rank them as
Array
(
[18] => 0.6667 //1
[228] => 0.3333 //2
[25] => 0.3333 //2
[568] => 0.3333 //2
[762] => 0 //3
[740] => 0 //3
[742] => 0 //3
)
I have tried using following code:
arsort($rank);
foreach ($rank as $k => $v) {
$i=1;
foreach ($rank as $k1 => $v1) {
if($v==$v1){
$newrank[$k]=$i;
}
else{
$i++;
}
}
}
But it gives me result
Array
(
[18] => 0.6667 //1
[228] => 0.3333 //2
[25] => 0.3333 //2
[568] => 0.3333 //2
[762] => 0 //5
[740] => 0 //5
[742] => 0 //5
)
I am unable to rectify why rank is increasing from 2 to 5.
Please help.
Upvotes: 1
Views: 1000
Reputation: 2347
It's Done..
foreach ($rank as $k => $v) {
$i=1;
foreach (array_unique($rank) as $k1 => $v1) {
if($v==$v1){
$newrank[$k]=$i;
}
else{
$i++;
}
}
}
Upvotes: 1
Reputation: 780818
You don't need nested loops. Just iterate through the array, and increment $i
whenever the score changes.
$newrank = array();
$i = 0;
$last_v = null;
foreach ($rank as $k => $v) {
if ($v != $last_v) {
$i++;
$last_v = $v;
}
$newrank[$k] = $i;
}
Upvotes: 2