Considering you are using Laravel and you know how to use collections. This answer inspired from Adam Wathan's book.
$scores = collect([
['score' => 80, 'name' => 'a'],
['score' => 85, 'name' => 'b'],
['score' => 80, 'name' => 'k'],
['score' => 75, 'name' => 'h'],
['score' => 90, 'name' => 'w'],
['score' => 90, 'name' => 'v'],
['score' => 50, 'name' => 'r'],
['score' => 45, 'name' => 't'],
]);
function rankandscore($scores){
return collect($scores)
->sortByDesc('score')
->zip(range(1, $scores->count()))
->map(function ($scoreAndRank){
list($score, $rank) = $scoreAndRank;
return array_merge($score, [
'rank' => $rank
]);
})
->groupBy('score')
->map(function ($tiedScores){
$lowestRank = $tiedScores->pluck('rank')->min();
return $tiedScores->map(function ($rankedScore) use ($lowestRank){
return array_merge($rankedScore, [
'rank' => $lowestRank,
]);
});
})
->collapse()
->sortBy('rank');
}
$score = rankandscore($scores);
dd($score);
// will give output like this.
[
['score' => 90, 'name' => 'w', 'rank' => 1],
['score' => 90, 'name' => 'v', 'rank' => 1],
['score' => 85, 'name' => 'b', 'rank' => 3],
['score' => 80, 'name' => 'a', 'rank' => 4],
['score' => 80, 'name' => 'k', 'rank' => 4],
['score' => 75, 'name' => 'h', 'rank' => 6],
['score' => 50, 'name' => 'r', 'rank' => 7],
['score' => 45, 'name' => 't', 'rank' => 8],
]
You can use this function to modify according to your needs
More Info https://laravel.com/docs/5.5/eloquent-collections