phpsortingphp-7.0

How can I sort an alphanumerical Multidimensional Array in php?


I have some json filenames in an multidimensional array, created like this: $files[] = array("name" => $file, "type" => "json") that I want to sort ascending like this:

1.File
2.File
3.File
10.File
11.File

If I order them using php sort($files) function they will be ordered like this:

1.File
10.File
11.File
2.File
3.File

If however I use natsort($files) that quote: orders alphanumeric strings in the way a human being would (php.net), I get a total mess:

3.File
2.File
10.File
1.File
11.File

Is there some better approach to order an array using php functions? Or do I have to build a custom sorting function. The server is running PHP 7.0.


Solution

  • You use multidimensional array, as you can see PHP have an error (Array to string conversion), you need to use usort for that task like:

    $array = array(
        array("name"=>'1.File', "type" => "json"),
        array("name"=>'2.File', "type" => "json"),
        array("name"=>'3.File', "type" => "json"),
        array("name"=>'10.File', "type" => "json"),
        array("name"=>'11.File', "type" => "json"),
        );
    usort($array, function($a, $b) {
        return ($a['name'] > $b['name'])
               ? 1 
               : ($a['name'] < $b['name'])
                 ? -1 
                 : 0;
    });
    print_r($array);
    

    Your fiddle edited

    Reference:


    As @u_mulder suggest strnatcasecmp will improve the code like:

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

    Reference: