Filter an array of objects

Quite often I might have an array of objects, be it from a db query or some json object, and I want to filter that list in a particular way.  Lots of times I would find myself doing the same old thing; creating a new array, looping and looping until all I had left was what matched my filter.

I’m sure you’ve been there and done it a thousand times, too.

Well, this little function should help that task out a lot!

Say I had an array of people objects and wanted only those people who’s name was Bob and was aged 35, I could do something as simple as:

$filtered = ofilter($items, ['name' => 'Bob', 'age' => 35]);

Or maybe something a little tricker; I wanted to get anyone whose age was between 18 and 35 (inclusive):

$filtered = ofilter($items, ['age' => function($age) { return ($age >= 18 && $age < = 35); }]);

Pretty easy, eh?

Here’s the code – it’s a GitHub gist, so feel free to fork and improve!
Continue reading “Filter an array of objects”

Did you like this? Share it:

Sorting an array of objects by one or more object property

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
Did you like this? Share it: