dongpixi2648 2013-09-24 10:38
浏览 45
已采纳

PHP - 排序多维数组

i'm Fabio Masino and i'm italian, so my English may be not perfect.

I would like to realize a method for sorting football groups

  • by points (sorted as numbers, in descending order),
  • then by goals scored (sorted as numbers, in descending order),
  • then by name (sorted as strings in ascending order).

For example, if i have this multi-dimensional array:

$group=array(
       array("Juve", 15, 45), // the values are name, points and goals scored
       array("Inter", 21, 40),
       array("Milan", 15, 50)
      );

I would like to have this result:

 $group=array(
           array("Inter", 21, 40),
           array("Milan", 15, 50),
           array("Juve", 15, 45)
          );

Thank you in advance and best regards.

  • 写回答

4条回答 默认 最新

  • dongzhila3786 2013-09-24 10:44
    关注

    Points is the second element of each subarray, right? If so, then do this

    function CustomSort($a, $b)
    {
        return $a[1] < $b[1] ? -1 : 1;
    }
    
    usort($group, 'CustomSort');
    

    If you want to focus on other criteria like names and goals, then just change the numeric array index to the number that represents each criteria in each subarray. For example, sorting names would just be

    function NameSort($a, $b)
    {
        return $a[0] > $b[0] ? -1 : 1;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?