phparrayssortingobjectnatural-sort

How do you natsort() by a column of an array of objects?


I have an array of objects that looks like this:

$result = [
    5 => (object)['id' => 173, 'name' => 'Silo 1'],
    6 => (object)['id' => 174, 'name' => 'Silo 10'],
    7 => (object)['id' => 175, 'name' => 'Silo 11'],
    11 => (object)['id' => 179, 'name' => 'Silo 2'],
    12 => (object)['id' => 180, 'name' => 'Silo 3']
];

I'm trying to figure out how to sort these based on the name

Things I've tried:

usort($result, function($a, $b)
{
    if ($a->name == $b->name) return 0 ;
    return ($a->name < $b->name) ? -1 : 1 ;
});

and

usort($result, function($a, $b)
{
    strnatcmp($a->name, $b->name); // return (0 if ==), (-1 if <), (1 if >)
});

Nothing is giving me my desired output which I want to be this:

Silo 1
Silo 2
Silo 3
Silo 10
Silo 11

What am I doing wrong?


Solution

  • You're not returning your strnatcmp results, so the PHP will assume a NULL return value:

    usort(...) {
       return strnatcmp(...);
       ^^^^^^
    }