PHP Multidimensional Array Sort

I can’t take credit for this, but I wanted to share this quick PHP tip (and make sure I have it for later too of course). Ever run into a situation where you needed to alphabetize a multidimensional array by one of the inner values? Well I have and I found the solution based on a StackOverflow (PROGRAMMER’S BEST FRIEND) thread.

Say you had this array:

<?php
$employees = array(
   144 => array('name' => 'Sally Joe'),
   146 => array('name' => 'John Deer'),
   155 => array('name' => 'Sakura Kinomoto')
);
?>

….and you wanted to sort an array by the name? Well you can’t do that easily with any of the ksort or asorts and etc. Here’s a custom usort

usort($employees, function($a, $b) {
 return $a['name'] - $b['name'];
 });

It’s pretty easy. The $employees is the array and the ‘name’ is the key I want the array sorted by. Run this and I get the array sorted by the name.

<?php
$employees = array(
   146 => array('name' => 'John Deer'),
   155 => array('name' => 'Sakura Kinomoto'),
   144 => array('name' => 'Sally Joe')
);
?>

This as a PHP 5.3 version. There are other PHP version functions in the StackOverflow thread I found this one. I can just say that the 5.3 one worked like a charm!

EDIT:

The above function doesn’t like DateTime comparisons. You need to change it with strtotime(). Here’s an update function with Date/Time comparison;

usort($events, function($a, $b){
 return strtotime($a['date']->format('Y-m-d')) - strtotime($b['date']->format('Y-m-d'));
 });