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.