Multidimensional Array Sorting in PHP (sorting arrays of arrays)

For today’s PHP coding trick, the function usort is your friend, though I found the PHP documentation wanting on this topic.

Basically, you have an array of arrays (multidimensional) and you want to sort the first array by the values in the secondary arrays.  In my case, I had an array of 3 value associative arrays (title, link, date).  I wanted to sort the primary array by the datetimes found in the 2nd array.  Turns out, this is incredibly easy using usort.

Just create a comparative function that will take two children arrays and compare two elements.  In my case, comparing articles (or more specifically, the dates):

function compare_times($article_one, $article_two) {
 if ( $article_one['Date'] == $article_two['Date'] )
 return 0;
 else if ( $article_one['Date'] < $article_two['Date'] )
 return 1;
 else
 return -1;
 }

Then… just call that by giving usort two parameters: the master array and the compare function name as a string:

usort($todays_stories[$section], 'compare_times');

(N.B. In my case above, I was using a three dimensional array, but only sorting the 2nd dimension ($section) by the times (more specifically the ‘Date’ key) in the third dimension.  The first dimension went unsorted/untouched.  This was inside of a foreach loop, so each $section was sorted independently from most recent article to oldest article).

Hope this helps — comment below if you have questions.

Targeting the Long Tail of Search

Lately, I’ve been using this blog to post about simple things that don’t have any useful (or at least clear) results in Google.  This include tips and tricks on platforms like WordPress and Magento, or some straightforward advice for beginners in PHP, MySQL, or whatever tool I’m using at the time of writing.

If I’m stumped on something for awhile, and eventually discover a solution, I’ll post it.  If I find a partial or unclear solution on the web, I’ll try to include a better answer here.

The point is, I’m not trying to reinvent the wheel.  The goal is to offer up something that is hopefully unique and helpful to each visitor that lands here.  As a result, this blog isn’t really readable in serial format (using RSS, for instance).

Despite focusing on the long tail of search, my number one most visited blog post is still the Edible Flying Spaghetti Monster.  Go figure.