使用其中一个值对多维数组进行排序,同时遵循其顺序 PHP


sort multidimension array using one of the values while respecting its order php

我有这个数组,它已经按"名称"ASC排序。

array 
  0 => 
    array
      'id' => '4'
      'name' => 'iPad'
      'games' => 5
  1 => 
    array
      'id' => '5'
      'name' => 'iPhone'
      'games' => 5
  2 => 
    array
      'id' => '6'
      'name' => 'Nintendo DS'
      'games' => 5
  3 => 
    array
      'id' => '1'
      'name' => 'Playstation 2'
      'games' => 2
  4 => 
    array
      'id' => '7'
      'name' => 'Playstation 3'
      'games' => 2
  5 => 
    array
      'id' => '7'
      'name' => 'Xbox 360'
      'games' => 1
如果"游戏"

的值相同,我希望按"游戏"的值排序,同时尊重排序的"名称"的顺序。

结果应如下所示:

array
  0 => 
    array
      'id' => '7'
      'name' => 'Xbox 360'
      'games' => 1
  1 => 
    array
      'id' => '1'
      'name' => 'Playstation 2'
      'games' => 2
  2 => 
    array
      'id' => '7'
      'name' => 'Playstation 3'
      'games' => 2
  3 => 
    array
      'id' => '4'
      'name' => 'iPad'
      'games' => 5
  4 => 
    array
      'id' => '5'
      'name' => 'iPhone'
      'games' => 5
  5 => 
    array
      'id' => '6'
      'name' => 'iPod Touch'
      'games' => 5

我几乎尝试了所有排序函数和用户定义的比较函数,但找不到合适的。

如果可能的话,如果我想要"游戏"DESC,同时在游戏价值相同的情况下保持排序的"名称"ASC,我该如何处理它?例:

array
  0 => 
    array
      'id' => '6'
      'name' => 'Nintendo DS'
      'games' => 5
  1 => 
    array
      'id' => '5'
      'name' => 'iPhone'
      'games' => 5
  2 => 
    array
      'id' => '4'
      'name' => 'iPad'
      'games' => 5
  3 => 
    array
      'id' => '1'
      'name' => 'Playstation 2'
      'games' => 2
  4 => 
    array
      'id' => '7'
      'name' => 'Playstation 3'
      'games' => 2
  5 => 
    array
      'id' => '7'
      'name' => 'Xbox 360'
      'games' => 1
usort($array, function ($a, $b) {
    if ($a['games'] == $b['games']) {
        return strcmp($a['name'], $b['name']);
    } else {
        return $a['games'] - $b['games'];
    }
});

还有其他使用自定义比较函数的方法,但最简单的方法是使用 array_multisort

首先使用要作为数组排序依据的键创建数组。然后向这些数组提供排序参数以array_multisort

// first collect the sorting keys
// ensure that $thearray[$n]['key'] corresponds to $sortkey[$n]
$games = array();
$name = array();
foreach ($thearray as $item) {
    $games = $item['games'];
    $name = $item['name'];
}
// now sort
array_multisort($games, SORT_NUMERIC, SORT_ASC,
                $name, SORT_STRING, SORT_ASC,
                $thearray);
// $thearray is now sorted first by games, then by name.