Sorting an array of objects by field makes no difference

时间:2019-01-09 21:40:16

标签: php arrays function sorting

I have this array called $pages. Inside, we have objects with several fields. One of these fields is title.

I want to sort alphabetically by title.

Inside a class called PLUGIN_PAGES I declare this...

public function mySort($a, $b)
{
return $a->title < $b->title;
}

inside another method I call

 usort ($pages, array("PLUGIN_PAGES", "mySort"));

No error. It appears to run but $pages is still not sorted.

Any ideas?

1 个答案:

答案 0 :(得分:5)

Your function should return an integer less than zero 0, equal to 0, or greater than 0 depending on the comparison. You can do this shorthand with the spaceship operator:

public function mySort($a, $b)
{
    return $a->title <=> $b->title;
}

This is essentially equivalent to:

public function mySort($a, $b)
{
    if ($a->title < $b->title) {
        return -1;
    }
    if ($a->title > $b->title) {
        return 1;
    }
    return 0;
}

For older versions of PHP, you can use @Dharman's suggestion:

public function mySort($a, $b)
{
    return strcmp($a->title, $b->title);
}