dsdeeaquu38538545 2017-10-16 14:51 采纳率: 100%
浏览 91

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

  • 写回答

1条回答 默认 最新

  • dpowt82802 2017-10-16 16:04
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计