PHP - Naturally Sort Nested Arrays by Key

07 Mar 2016

Let’s say we have an array of objects like so that are coded incrementally like so: OBJ1, OBJ2, OBJ3..

One problem with MySQL is that there’s no easy way to naturally sort a returned array, so if you have 15 objects, you’ll end up with an array like:

array(26) {
  [0]=>
  array(2) {
    ["key"]=>
    string(3) "OBJ1"
    ["value"]=>
    string(21) "Something something"
  }
  [1]=>
  array(2) {
     ["key"]=>
    string(3) "OBJ10"
    ["value"]=>
    string(21) "Something something"
  }
  [2]=>
  array(2) {
    ["key"]=>
    string(3) "OBJ11"
    ["value"]=>
    string(21) "Something something"
  }
  [3]=>
  array(2) {
     ["key"]=>
    string(3) "OBJ2"
    ["value"]=>
    string(21) "Something something"
  }
}

The problem is that MySQL is sorting the keys in the manner of a computer, not a human. Not desirable.

Luckily, we’ve got the benefit of naturally sorting things as a human would.

Use the following function to sort the array by a nested key (such as “key” in the example above)

usort($array, function ($a, $b) {
            return strnatcasecmp($a["key"], $b["key"]);
        });

Enjoy :)