0

I have an array like this:

Array ( 
    [0] => Array ( 
        [tag] => /nn 
        [count] => 55
    ) 
    [1] => Array ( 
        [tag] => /vb 
        [count] => 7
    )
) 

and I want to sort it. In this example it's already like I want it to be. Sorted by count. What if it was reverse ordered? What function is there to sort it?

Thanks a lot.

Toto
  • 86,179
  • 61
  • 85
  • 118
Andrew
  • 6,008
  • 15
  • 55
  • 92

4 Answers4

1
$count = array();

// Obtain a list of columns
foreach ($array as $key => $row) {
    $count[$key]  = $row['count'];
}

//sort by count descending
array_multisort($count, SORT_DESC, $array);

DOC

Naftali
  • 142,114
  • 39
  • 237
  • 299
1

Use usort() like this:

 usort( $array, function( $a, $b ) { 
     if ( $a['count'] == $b['count'] ) 
         return 0;

     return ( $a['count'] > $b['count'] ? -1 : 1 );
 }

Reverse the > if you want it to reverse the order.

Rijk
  • 10,704
  • 3
  • 28
  • 44
1

Check this code

function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
    $sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
    $ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($your_array,"order");

Or

I usually use usort, and pass my own comparison function. In this case, it is very simple:

function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');

Hope you can find your answer. Mark my answer and point me up, thanks.

Emaad Ali
  • 1,453
  • 4
  • 19
  • 41
0

I 've written a function here that allows you to select which key you want to sort with. You can even specify multiple keys for secondary, tertiary, etc sort.

With this make_comparer function, you would sort like this:

uasort($array, make_comparer('count'));
Community
  • 1
  • 1
Jon
  • 413,451
  • 75
  • 717
  • 787