需求:有以下数组,按照 volume 降序排列,当 volume 相同时,按 edition 升序排列。

array:6 [
  0 => array:2 [
    "volume" => 67
    "edition" => 2
  ]
  1 => array:2 [
    "volume" => 86
    "edition" => 1
  ]
  2 => array:2 [
    "volume" => 85
    "edition" => 6
  ]
  3 => array:2 [
    "volume" => 98
    "edition" => 2
  ]
  4 => array:2 [
    "volume" => 86
    "edition" => 6
  ]
  5 => array:2 [
    "volume" => 67
    "edition" => 7
  ]
]

PHP 提供了 array_multisort 函数用来实现多数组排序或者数组多条件排序,上面需求的实现代码如下:

$data = [
    ['volume' => 67, 'edition' => 2],
    ['volume' => 86, 'edition' => 1],
    ['volume' => 85, 'edition' => 6],
    ['volume' => 98, 'edition' => 2],
    ['volume' => 86, 'edition' => 6],
    ['volume' => 67, 'edition' => 7],
];
$volume = array_column($data,'volume');
$edition = array_column($data,'edition');
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
var_dump($data);

输出(注意与示例数组的区别):

array:6 [
  0 => array:2 [
    "volume" => 98
    "edition" => 2
  ]
  1 => array:2 [
    "volume" => 86
    "edition" => 1
  ]
  2 => array:2 [
    "volume" => 86
    "edition" => 6
  ]
  3 => array:2 [
    "volume" => 85
    "edition" => 6
  ]
  4 => array:2 [
    "volume" => 67
    "edition" => 2
  ]
  5 => array:2 [
    "volume" => 67
    "edition" => 7
  ]
]
(adsbygoogle = window.adsbygoogle || []).push({});