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
  • 83,193
  • 59
  • 77
  • 109
Andrew
  • 5,690
  • 14
  • 52
  • 88

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 aka Neal
  • 138,754
  • 36
  • 231
  • 295
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,216
  • 2
  • 27
  • 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,415
  • 4
  • 18
  • 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
  • 396,160
  • 71
  • 697
  • 768