php / laravel - 如何根据最高编号和数字排列数组

I have a table with marks of students in it. i have 2 record

student a = 90;
student b = 85;

I want to get the all the results for the total score of the students and then give the students positions in the class e.g

student a = 90; //first position
student b = 85; //second position

i have a column called position which is null after saving the total score of the students how can i check who is higher/lower and give them positions

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