Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you natsort an array of objects?

I have an array of objects that looks like this:

Array
(    
[5] => stdClass Object
    (
        [id] => 173
        [name] => Silo 1
    )

[6] => stdClass Object
    (
        [id] => 174
        [name] => Silo 10
    )

[7] => stdClass Object
    (
        [id] => 175
        [name] => Silo 11
    )

[11] => stdClass Object
    (
        [id] => 179
        [name] => Silo 2
    )

[12] => stdClass 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?

like image 532
Ryan Mortier Avatar asked Feb 18 '23 13:02

Ryan Mortier


1 Answers

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

usort(...) {
   return strnatcmp(...);
   ^^^^^^
}
like image 160
Marc B Avatar answered Feb 27 '23 23:02

Marc B