按多维数组分组和排序

Group by and sort by a multidimensional array

我有一个数组

<?php

$arr = [
          ['price'=>100, 'rank'=>3],
          ['price'=>55000, 'rank'=>4],
          ['price'=>500, 'rank'=>5],
          ['price'=>130, 'rank'=>3],
          ['price'=>25000, 'rank'=>4],
          ['price'=>50000, 'rank'=>4],
          ['price'=>120, 'rank'=>3],
          ['price'=>1000, 'rank'=>5],
];

我希望它首先按 rank 降序分组,然后在该组中按价格降序排列。

      ['price'=>1000, 'rank'=>5],
      ['price'=>500, 'rank'=>5],
      ['price'=>55000, 'rank'=>4],
      ['price'=>50000, 'rank'=>4],
      ['price'=>25000, 'rank'=>4],
      ['price'=>130, 'rank'=>3],
      ['price'=>120, 'rank'=>3],
      ['price'=>100, 'rank'=>3],

我用 uasort 函数和 spaceship 运算符尝试过,但我没能成功。

您可以使用array_multisort

$arr = [
          ['price'=>100, 'rank'=>3],
          ['price'=>55000, 'rank'=>4],
          ['price'=>500, 'rank'=>5],
          ['price'=>130, 'rank'=>3],
          ['price'=>25000, 'rank'=>4],
          ['price'=>50000, 'rank'=>4],
          ['price'=>120, 'rank'=>3],
          ['price'=>1000, 'rank'=>5],
];

$price  = array_column($arr, 'price');
$rank = array_column($arr, 'rank');

// Sort the data with price descending, rank descending
// Add $data as the last parameter, to sort by the common key
array_multisort($rank, SORT_DESC, $price, SORT_DESC, $arr);

echo '<pre>';
print_r($arr);
die;

你可以查看Demo

$arr = [
          ['price'=>100, 'rank'=>3],
          ['price'=>55000, 'rank'=>4],
          ['price'=>500, 'rank'=>5],
          ['price'=>130, 'rank'=>3],
          ['price'=>25000, 'rank'=>4],
          ['price'=>50000, 'rank'=>4],
          ['price'=>120, 'rank'=>3],
          ['price'=>1000, 'rank'=>5],
];
    uasort($arr, function($a,$b)
    {
        return $b['rank'] - $a['rank'] ?: $b['price'] - $a['price'];
    });
print_r($arr);

使用 usort 和宇宙飞船运算符:

$arr = [
          ['price'=>100, 'rank'=>3],
          ['price'=>55000, 'rank'=>4],
          ['price'=>500, 'rank'=>5],
          ['price'=>130, 'rank'=>3],
          ['price'=>25000, 'rank'=>4],
          ['price'=>50000, 'rank'=>4],
          ['price'=>120, 'rank'=>3],
          ['price'=>1000, 'rank'=>5],
];

usort($arr,function($a,$b){
  return $b['rank'] <=> $a['rank'] ?: $b['price'] <=> $a['price'];
});

var_dump($arr);

编辑: 对于 array_multisort 的解决方案,我推荐这种表示法。她很好理解:

array_multisort(
  array_column($arr, 'rank'), SORT_DESC, 
  array_column($arr, 'price'), SORT_DESC, 
  $arr
);