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?
You're not returning your strnatcmp results, so the PHP will assume a NULL
return value:
usort(...) {
return strnatcmp(...);
^^^^^^
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With