-1

我有一个数组

<?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],
];

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

      ['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 函数,但我无法成功。

4

3 回答 3

3

您可以使用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;

您可以查看演示

于 2019-12-04T07:23:08.773 回答
1
$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);
于 2019-12-04T07:24:55.107 回答
1

使用 usort 和 spaceship 运算符:

$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
);
于 2019-12-04T07:25:34.263 回答