Sorting an array of objects by one or more object property

Last modified date

Comments: 3

Quite often I find myself having an array of objects and needing to sort that array of objects by property (either one property or multiple)…

Imagine, for example, getting a large result set from your database and ordering in the query just takes too long. Or perhaps you’re getting results from a web service and that service doesn’t return the results in the order you’d like to use. Have you ever found yourself in that situation, too? On looking at the usort documentation one day I came across a comment by someone called Will Shaver that did almost what I wanted. With a little adaptation for my own use (being able to change the sort order, for example), it has become one of my favourite functions to use for sorting.

loading gist...

Now a few cools things about the function:

  1. It uses anonymous/lambda functions (or closures, whatever your prefer to call them), and that’s just plain fun
  2. You can sort on more than one property and because the sorting is recursive, it’ll sort the second property within the confines of the first, the third within the confines of the second, and so on. Think sorting in SQL
  3. You can sort in ascending or descending order for any of the properties
  4. It retains key associations so you could use this on an associative array of objects
  5. If the parameter you want to sort on is an array itself then you can use any value (by specifying it’s key) in that array as the sorting value

Share