分组和排序php数组

时间:2017-09-07 14:37:29

标签: php arrays sorting

我有一个数组($ myArray)

Array ( [0] => 
          Array ( [0] => new
                  [1] => NFL930
                  [2] => Ohio
                  ...
                )
        [1] =>
          Array ( [0] => new
                  [1] => MLB382
                  [2] => Florida
                  ...
                )
        [2] =>
          Array ( [0] => new
                  [1] => MLB101
                  [2] => Vermont
                  ...
                )
        [3] =>
          Array ( [0] => new
                  [1] => NFL732
                  [2] => Alabama
                  ...
                )
        [4] =>
          Array ( [0] => old
                  [1] => MLB490
                  [2] => Texas
                  ...
                )
        [5] =>
          Array ( [0] => old
                  [1] => MLB821
                  [2] => Atlanta
                  ...
                )
        [6] =>
          Array ( [0] => old
                  [1] => NFL293
                  [2] => Maine
                  ...
                )
        .....
     )

我有一个函数可以对上面显示的[0]索引进行排序,因此所有“新”条目都是第一个,然后列出所有“旧”条目。

usort($myArray, function($a, $b) use ($myValues){
    return $myValues[$a[0]] - $myValues[$b[0]];
  });

数组$ myValues看起来像

Array ( [New] => 0 [Old] => 1 [Other] => 2 )

我想保持[0]索引排序,因为显示所有数组的新的第一个,然后显示数组有旧的等等。然后我想在具有MLB的那些之前显示具有“NFL”的那些。例如,所需的输出将是

Array ( [0] => 
      Array ( [0] => new
              [1] => NFL930
              [2] => Ohio
              ...
            )
    [1] =>
      Array ( [0] => new
              [1] => NFL732
              [2] => Alabama
              ...
            )
    [2] =>
      Array ( [0] => new
              [1] => MLB101
              [2] => Vermont
              ...
            )
    [3] =>
      Array ( [0] => new
              [1] => MLB382
              [2] => Florida
              ...
            )
    [4] =>
      Array ( [0] => old
              [1] => NFL293
              [2] => Maine
              ...
            )
    [5] =>
      Array ( [0] => old
              [1] => MLB821
              [2] => Atlanta
              ...
            )
    [6] =>
      Array ( [0] => old
              [1] => MLB490
              [2] => Texas
              ...
            )
    .....
 )

1 个答案:

答案 0 :(得分:1)

您可以修改您的用户:

usort($myArray, function($a, $b) use ($myValues){
   if ($myValues[$a[0]] - $myValues[$b[0]] == 0) {
       return strcmp($a[1],$b[1]);
   }
   return $myValues[$a[0]] - $myValues[$b[0]];
});

这将根据索引1对条目进行排序,如果它们在索引0上相同(这意味着NFL在MLB之前,但NFL001在NFL002之前)