PHP数组按内部数组的值进行多排序


php array multisort by inner arrays value

我正在尝试在PHP中排序投票列表。

列表是一个数组,包含类对象:

Array
(
    [0] => VotedSong Object
        (
            [title] => SimpleXMLElement Object
                (
                    [0] => bbh - bghs dsdw
                )
            [votes] => SimpleXMLElement Object
                (
                    [0] => 6
                )
            [key] => SimpleXMLElement Object
                (
                    [0] => bbh--0
                )
        )
    [1] => VotedSong Object
        (
            [title] => SimpleXMLElement Object
                (
                    [0] => aaa - bbb
                )
            [votes] => SimpleXMLElement Object
                (
                    [0] => 4
                )
            [key] => SimpleXMLElement Object
                (
                    [0] => aaa--0
                )
        )
    [2] => VotedSong Object
        (
            [title] => SimpleXMLElement Object
                (
                    [0] => wdewv - qwdqs
                )
            [votes] => SimpleXMLElement Object
                (
                    [0] => 3
                )
            [key] => SimpleXMLElement Object
                (
                    [0] => wdewv--0
                )
        )
    [3] => VotedSong Object
        (
            [title] => SimpleXMLElement Object
                (
                    [0] => Hsg and fdSv - aGamaama
                )
            [votes] => SimpleXMLElement Object
                (
                    [0] => 2
                )
            [key] => SimpleXMLElement Object
                (
                    [0] => hsgandfdsv--0
                )
        )
)

我设法通过工作良好的->key进行排序:

usort($votedsongs, function ($a, $b) { return $b->votes - $a->votes; });

但在此之后,我还需要另一个sort-function来对->title中具有相同票数的歌曲进行排序。

我已经找到了一些解决类似问题的方法,但是它们对我都不起作用。

对此有什么想法吗?

听起来您想要通过votes排序数组中的VotedSong对象,然后通过title(拼写错误为titel)。如果是这样,可以这样做:

usort($votedsongs, function ($a, $b) {
    if ($b->votes == $a->votes) {
        return ($a->title < $b->title) ? -1 : 1;
    }
    return $b->votes - $a->votes;
});

感谢splash58为这个解决方案:

if (!($r = $b->votes - $a->votes)) $r = strcmp($b->title, $a->title); return $r;

我修改了字母排序为不区分大小写,并切换了$a->title$b->title -就是这样:

usort($votedsongs, function ($a, $b) { 
    if (!($r = $b->votes - $a->votes)) $r = strcasecmp($b->title, $a->title); return $r; 
});