douhui8025 2014-07-16 08:36
浏览 29
已采纳

准确地从单维数组中设置排名

I would like to display some array data in relation to a competition, each player is ranked by the number of points they have, however if a player has the same amount of points to somebody else they should both have the exact same ranking position.

For instance...

  1. 1st Bob 500pts
  2. 2nd Joe 350pts
  3. 3rd Tom 250pts
  4. 3rd Tim 250pts
  5. 5th Jay 100pts

In this instance, as Tom & Tim have the exact same number of points they should be joint third, making the next person down 5th (rather than 4th), can anyone suggest the best way to achieve this with a simple array similar to follows

array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');

Can anyone suggest the 'cleanest' solution for achieving this

  • 写回答

4条回答 默认 最新

  • douduoquan2824 2014-07-16 08:59
    关注

    This code will work for you:

    1. $array = array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
    2. arsort($array, SORT_NUMERIC);
    3. $previousPoints = null;
    4. $position = $total = 1;
    5. foreach($array as $name=>$points) {
    6. if ($points != $previousPoints) {
    7. $position = $total;
    8. }
    9. echo $position.' '.$name.' '.$points."
    10. ";
    11. $previousPoints = $points;
    12. $total++;
    13. }

    Online demo here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部