Posted By


browncardigan on 02/05/10

Tagged


Statistics


Viewed 461 times
Favorited by 0 user(s)

orderMultiAssocArray


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

Orders a multi-dimensional array by one of it's fields.

There is also the option to treat this like an SQL-style 'order by' query with the $field value passed in (ie. 'user_id desc') to do reverse ordering.


Copy this code and paste it in your HTML
  1. function orderMultiAssocArray($array=array(), $field='', $keep_assoc=true) {
  2. if ($field != '') {
  3. if (strstr($field, ' desc')) {
  4. $field = str_replace(' desc', '', $field);
  5. $reverse = true;
  6. }
  7. else {
  8. $reverse = false;
  9. }
  10. $ar = array();
  11. foreach ($array as $key => $a) {
  12. $ar[$key] = $a[$field];
  13. }
  14. if ($reverse) { arsort($ar); }
  15. else { asort($ar); }
  16. $array_redux = array();
  17. $counter=0;
  18. foreach ($ar as $k => $a) {
  19. $key = $keep_assoc ? $k : $counter;
  20. $array_redux[$key] = $array[$k];
  21. $counter++;
  22. }
  23. $array = $array_redux;
  24. }
  25. return $array;
  26. }

URL: http://bettesmidler.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.