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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效