4

我有一个看起来像这样的对象数组:

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
    )
)

我试图弄清楚如何根据name

我尝试过的事情:

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

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

没有什么能给我我想要的输出:

Silo 1
Silo 2
Silo 3
Silo 10
Silo 11

我究竟做错了什么?

4

1 回答 1

8

您没有返回 strnatcmp 结果,因此 PHP 将假定NULL返回值:

usort(...) {
   return strnatcmp(...);
   ^^^^^^
}
于 2013-02-12T14:46:57.617 回答