Sort by specific array key


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function array_sort($array, $on, $order=SORT_ASC)
  2. {
  3. $new_array = array();
  4. $sortable_array = array();
  5.  
  6. if (count($array) > 0) {
  7. foreach ($array as $k => $v) {
  8. if (is_array($v)) {
  9. foreach ($v as $k2 => $v2) {
  10. if ($k2 == $on) {
  11. $sortable_array[$k] = $v2;
  12. }
  13. }
  14. } else {
  15. $sortable_array[$k] = $v;
  16. }
  17. }
  18.  
  19. switch ($order) {
  20. case SORT_ASC:
  21. asort($sortable_array);
  22. break;
  23. case SORT_DESC:
  24. arsort($sortable_array);
  25. break;
  26. }
  27.  
  28. foreach ($sortable_array as $k => $v) {
  29. $new_array[$k] = $array[$k];
  30. }
  31. }
  32.  
  33. return $new_array;
  34. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.