Posted By

pruntrut on 05/14/12


Tagged

php array sorting


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tux-world


Sorting an multidimensional array


 / Published in: PHP
 

URL: http://www.codingforums.com/showthread.php?t=71904

The following shoud do it. pass the array, index is what element you want to sort on (in your case use 3). Then you can sort asc or desc, and weather you want to use natural sorting (the way a human would sort, 2 before 10) and lastly case sensitive or not if using natural sort. Only the first 2 args are needed, the rest will default.

  1. function sort2d ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE)
  2. {
  3. if(is_array($array) && count($array)>0)
  4. {
  5. foreach(array_keys($array) as $key)
  6. $temp[$key]=$array[$key][$index];
  7. if(!$natsort)
  8. ($order=='asc')? asort($temp) : arsort($temp);
  9. else
  10. {
  11. ($case_sensitive)? natsort($temp) : natcasesort($temp);
  12. if($order!='asc')
  13. $temp=array_reverse($temp,TRUE);
  14. }
  15. foreach(array_keys($temp) as $key)
  16. (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
  17. return $sorted;
  18. }
  19. return $array;
  20. }

Report this snippet  

You need to login to post a comment.