我有一张桌子上有学生的标记。我有2条记录
student a = 90;
student b = 85;
我想得到学生总分的所有结果,然后给学生在班上的位置,例如
student a = 90; //first position
student b = 85; //second position
我有一个名为position的列,在保存学生的总分后为空,我如何检查谁更高/更低并给他们职位
答案 0 :(得分:0)
考虑到您正在使用Laravel并且您知道如何使用集合。这个答案来自Adam Wathan的书。
$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],
]
您可以根据需要使用此功能进行修改