1

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
        )
)
loghum
  • 13
  • 3
  • possible duplicate of [Sort Multi-dimensional Array by Value](http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) – Thomas Ruiz Feb 12 '14 at 11:05

3 Answers3

1

Use usort with a user defined function like:

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;
  }
}
Jorge Barata
  • 2,227
  • 1
  • 20
  • 26
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
        )

)
ibondoc22
  • 106
  • 7
0

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

Once you figure out a method and have trouble executing it then you can ask a more specific question.

LauriK
  • 1,899
  • 15
  • 20