Sorted

Posted Thursday 22nd September, 2005

Sooner or later, whilst using arrays in PHP, you’re going to want to re-order the data. On a one-dimensional array this simply requires us to run one of the sort(), rsort(), asort() or ksort() commands (depending on what we are doing).

However, should we be using a mult-dimensional array, we need to use the array_multisort() PHP command.

If our array is a database result, it is usually a two-dimensional array arranged in rows but array_multisort() sorts using columns. For this reason we need to do some hefty work preparing our array for ordering. Because of this, I ended up writing this short function the other day:

<?php
function do_result_sort($arr_data, $str_column, $bln_desc = false)
{
  $arr_data                 = (array) $arr_data;
  $str_column               = (string) trim($str_column);
  $bln_desc                 = (bool) $bln_desc;
  $str_sort_type            = ($bln_desc) ? SORT_DESC : SORT_ASC;

  foreach ($arr_data as $key => $row)
  {
    ${$str_column}[$key]    = $row[$str_column];
  }

  array_multisort($$str_column, $str_sort_type, $arr_data);

  return $arr_data;
}
?>

This function basically allows me to reorganise a result set array by any column either DESC or ASC (however, only one column at a time - with a little hacking we could change that easily).

Since I’ve found this remarkably useful on occasion, I thought I’d share it with the world…

Update: Just realised that I didn’t give you an example of it in use. Consider that corrected:

< ?php
// Here's an array...
$arr_test = array(array('name' => 'tim', 'veg' => 'carrots'),
                  array('name' => 'rob', 'veg' => 'swede'),
                  array('name' => 'mark', 'veg' => 'brocolli'),
                  array('name' => 'apaul', 'veg' => 'sprouts'),
                  array('name' => 'russell', 'veg' => 'mushrooms'),
                  array('name' => 'stupot', 'veg' => 'leeks'));

// Stick it through our function to sort it...
$arr_test = do_result_sort($arr_test, 'name');
?>
Included in: Development, PHP

Categories:

  1. Accessibility
  2. Ajax
  3. Apache
  4. API
  5. Architecture
  6. Books
  7. Browsers
  8. CMS
  9. CouchDB
  10. CSS
  11. Design
  12. Development
  13. Django
  14. Email
  15. Events
  16. Gaming
  17. Grammar
  18. Hardware
  19. HTML
  20. HTTP
  21. Humour
  22. Idea
  23. Information Architecture
  24. JavaScript
  25. jQuery
  26. Life
  27. Linux
  28. Literature
  29. Mac OS X
  30. Meme
  31. Microformats
  32. Monday
  33. MySQL
  34. Networking
  35. News
  36. Personal
  37. Photoshop
  38. PHP
  39. Python
  40. Reference
  41. REST
  42. Science
  43. SEO
  44. Server
  45. Site
  46. Sitepimp
  47. Social
  48. Spelling
  49. Syndication
  50. Testing
  51. The Future
  52. Thoughts
  53. Tools
  54. Tutorials
  55. Typography
  56. UI
  57. UNIX
  58. Virtualisation
  59. Web
  60. Web Standards
  61. Widgets
  62. Wii
  63. Writing
  64. Xbox
  65. XHTML