php usort 使用用户自定义的比较函数对二维数组中的值进行排序

时间:2022-12-12 11:28:55

今天发现一个很好用二维数组排序的php方法,usort,推荐给大家,以后二维数组里面,要按照一个字段的值排序用这个方法简单高效,例如下面的数组:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
[guess_subject] => Array
    (
      [0] => Array
        (
          [subject_id] => 4587
          [game_id] => 9228
          [parent_category_id] => 78
          [subject_title] => 全场比赛两队总得分之和是
          [subject_date_time] => 1490668200
          [status] => 2
          [subject_answer] => 0
          [totle_join] => 0
          [max_nickname] =>
          [max_currency] =>
        )
 
      [1] => Array
        (
          [subject_id] => 4588
          [game_id] => 9228
          [parent_category_id] => 78
          [subject_title] => 本场比赛是否有加时赛
          [subject_date_time] => 1490668200
          [status] => 2
          [subject_answer] => 0
          [totle_join] => 0
          [max_nickname] =>
          [max_currency] =>
           
 
        )
 
      [2] => Array
        (
          [subject_id] => 4584
          [game_id] => 9228
          [parent_category_id] => 78
          [subject_title] => 第二节两队总得分之和是
          [subject_date_time] => 1490668200
          [status] => 1
          [subject_answer] => 0
          [totle_join] => 0
          [max_nickname] =>
          [max_currency] =>
        )
 
      [3] => Array
        (
          [subject_id] => 4585
          [game_id] => 9228
          [parent_category_id] => 78
          [subject_title] => 第三节两队总得分之和是
          [subject_date_time] => 1490668200
          [status] => 2
          [subject_answer] => 0
          [totle_join] => 0
          [max_nickname] =>
          [max_currency] =>
         )
    )

要按照status字段的升序排列的话,只需要这样写

?
1
2
3
4
5
6
7
8
9
10
11
12
foreach($data as $key => &$value) {
     // 按照status的升序排序,使用用户自定义的比较函数对数组中的值进行排序,
     // 本函数将用用户自定义的比较函数对一个数组中的值进行排序。 如果要排序的数组需要用一种不寻常的标准进行排序,那么应该使用此函数。
     // 在第一个参数小于,等于或大于第二个参数时,该比较函数必须相应地返回一个小于,等于或大于 0 的整数。
     usort($value['guess_subject'], function($a, $b){
       if ($a['status'] == $b['status'])
         return 0;
       return ($a['status'] < $b['status']) ? -1 : 1;
     });
     
   }
   return $data;

就会按照status的 升序排列啦, status=1 的数组单元会排在前面