简体   繁体   English

对多维数组排序两次

[英]Sorting multidimensional array twice

I have a multidimensional array that need to be sorted. 我有一个需要排序的多维数组。 I want this array first sorted based on count from high to low. 我希望此数组首先根据从高到低的计数进行排序。 But when count has the same value, sort by city alphabetically. 但是,当计数具有相同的值时,请按字母顺序按城市排序。 I don't know how to do this. 我不知道该怎么做。

The multidimensional array: 多维数组:

Array
    (

    [0] => Array
        (
            [id] => 2
            [city] => c
            [count] => 5 
        )

    [1] => Array
        (
            [id] => 3
            [city] => b
            [count] => 10
        )

    [2] => Array
        (
            [id] => 4
            [city] => a
            [count] => 5
        )
)

Any ideas? 有任何想法吗?

EDIT: 编辑:

this is the result that i want: 这是我想要的结果:

Array
    (

    [0] => Array
        (
            [id] => 3
            [city] => b
            [count] => 10 
        )

    [1] => Array
        (
            [id] => 4
            [city] => a
            [count] => 5
        )

    [2] => Array
        (
            [id] => 2
            [city] => c
            [count] => 5
        )
)

Use usort with a user defined function like: usort与用户定义的函数一起使用,例如:

function($a, $b) {
  if($a['count'] === $b['count']) {
    if($a['city'] === $b['city']) {
      return 0;
    }
    return $a['city'] < $b['city'] ? -1 : 1;
  } else {
    return $a['count'] < $b['count'] ? -1 : 1;
  }
}

This is how i usually do it.. 这就是我通常的做法。

$test = array(array('id'=> '2', 'city'=> 'c', 'count' => '5'),array('id'=> '3', 'city'=> 'b', 'count' => '10'),array('id'=> '4', 'city'=> 'a', 'count' => '5'));

function cmp($a, $b){
    if($a['count'] == $b['count']){
        if($a['city'] == $b['city']){
            return 0;
        }return $a['city'] < $b['city'] ? -1 : 1;
    }else{
         return $a['count'] > $b['count'] ? -1 : 1;
    }
 }

uasort($test , 'cmp');

result 结果

Array
(
    [1] => Array
        (
            [id] => 3
            [city] => b
            [count] => 10
        )

    [2] => Array
        (
            [id] => 4
            [city] => a
            [count] => 5
        )

    [0] => Array
        (
            [id] => 2
            [city] => c
            [count] => 5
        )

)

PHP has many different methods and even a good overview page for exactly this kind of question: http://www.php.net/manual/en/array.sorting.php PHP有很多不同的方法,甚至对于这个问题,都有一个很好的概述页面: http : //www.php.net/manual/en/array.sorting.php

Once you figure out a method and have trouble executing it then you can ask a more specific question. 一旦找出方法并在执行时遇到麻烦,就可以提出更具体的问题。

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

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