简体   繁体   English

按多维数组分组和排序

[英]Group by and sort by a multidimensional array

I have an 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],
];

I want it to be firstly grouped by rank in descending order, and after that in that group ordered by price in descending order.我希望它首先按排名降序分组,然后在该组中按价格降序排列。

      ['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],

I tried it with uasort function with spaceship operator but I couldn't succeed.我用宇宙飞船操作员的 uasort 函数尝试了它,但我无法成功。

You can use array_multisort您可以使用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;

You can check 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);

With usort and the spaceship operator:使用 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);

Edit: For the solution with array_multisort I recommend this notation.编辑:对于带有 array_multisort 的解决方案,我推荐这种表示法。 She is very understandable:她非常理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM