1

我有这个数组,它已经按“名称”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
4

2 回答 2

2
usort($array, function ($a, $b) {
    if ($a['games'] == $b['games']) {
        return strcmp($a['name'], $b['name']);
    } else {
        return $a['games'] - $b['games'];
    }
});
于 2012-04-18T01:41:11.617 回答
0

还有其他使用自定义比较函数的方法,但最简单的方法是使用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.
于 2012-04-18T01:45:58.017 回答