phparrayssortingmultidimensional-arraynatural-sort

Naturally sort the rows of a 2d array by a column of alphanumeric values


I'm looking for a custom function that will respect the order of the array and sort it by the 'name' key. 'strcasecmp()' function doesn't understand alphanueric values as humans would read it. It thinks 'Apples 12' is a lesser value than 'Apples 5'. I tried this method but can't find a function to compare alphanumeric value:

$array = array(
    0 => array(
        'id' => 2,
        'type' => 'Apples',
        'name' => 'Apples 5',
    ),
    1 => array(
        'id' => 3,
        'type' => 'Grapes',
        'name' => 'Apples',
    ),
    2 => array(
        'id' => 4,
        'type' => 'Apples',
        'name' => 'Apples 4',
    ),
    3 => array(
        'id' => 5,
        'type' => 'Grapes',
        'name' => 'Apples 01',
    ),
    4 => array(
        'id' => 6,
        'type' => 'Apples',
        'name' => 'Apples 1',
    ),
    5 => array(
        'id' => 7,
        'type' => 'Grapes',
        'name' => 'Apples 12',
    )
);

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

foreach($array as $single) {
    echo $single['name'].'<br />';
}

Unexpected result from code above:

Apples
Apples 01
Apples 1
Apples 12
Apples 4
Apples 5

The result I wanted to achieve:

Apples
Apples 01
Apples 1
Apples 4
Apples 5
Apples 12

Solution

  • use strnatcasecmp() for natural ordering