Posted By

neshumah on 02/11/10


Tagged

php sort


Versions (?)

Multi Sort


 / Published in: PHP
 

sort by second column then first one

  1. <?
  2. //sort by second column then first one
  3. $orderBy=array('0'=>'asc', '1'=>'asc');
  4.  
  5. function KES_cmp($a, $b) {
  6. global $orderBy;
  7. $result= 0;
  8. foreach( $orderBy as $key => $value ) {
  9. if( $a[$key] == $b[$key] ) continue;
  10. $result= ($a[$key] < $b[$key])? -1 : 1;
  11. if( $value=='desc' ) $result= -$result;
  12. break;
  13. }
  14. return $result;
  15. }
  16.  
  17. $result= array();
  18. $result[]= array( 'first'=>6, 2);
  19. $result[]= array( 'first'=>3, 2);
  20. $result[]= array( 'first'=>1, 3);
  21. $result[]= array( 'first'=>1, 2);
  22. $result[]= array( 'first'=>6, 1);
  23.  
  24. print "</br<b>Source</b></br>";
  25. print_r($result);
  26.  
  27. usort($result, 'KES_cmp');
  28. print "</br<b>Result</b></br>";
  29. print_r($result);
  30. ?>

Report this snippet  

You need to login to post a comment.