Natural sorting of multi-dimensional array in PHP

What is natural sorting

Natural sort order is an ordering of strings in alphabetical order, except that multi-digit numbers are ordered as a single character. Natural sort order has been promoted as being more human-friendly (“natural”) than the machine-oriented pure alphabetical order.[1]

For example, in alphabetical sorting “z11” would be sorted before “z2” because “1” is sorted as smaller than “2”, while in natural sorting “z2” is sorted before “z11” because “2” is sorted as smaller than “11”.

Source: Wikipedia

Natural sorting in PHP

In php there is a function called natsort which does exactly that. It does not however work on multi-dimensional arrays.
For example:

$array = [
    "Entry 1" => ["sub" => "array"],
    "Entry 2" => ["sub" => "array"],
    "Entry 3" => ["sub" => "array"],
    "Entry 4" => ["sub" => "array"],
    "Entry 5" => ["sub" => "array"],
    "Entry 6" => ["sub" => "array"],
    "Entry 7" => ["sub" => "array"],
    "Entry 8" => ["sub" => "array"],
    "Entry 9" => ["sub" => "array"],
    "Entry 10" => ["sub" => "array"],
];
natsort($array);
var_dump($array);

Will yield something similar:

PHP Notice:  Array to string conversion in /home/code/NaturalSort.php on line 16

How to naturally sort multi-dimensional array in PHP

In order to properly do a natural sort on multi-dimensional array based on keys and maintaining relations you can use the following function:

array_multisort(array_keys($array), SORT_NATURAL, $array);

 

Be the first to comment

Leave a Reply

Your email address will not be published.


*