我正在尝试用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; });
但在此之后,我仍然需要另一个排序功能来排序那些具有相同票数->title
的歌曲。
我已经找到了一些解决问题的解决方案,但那些对我不起作用。
有关于此的任何想法吗?
答案 0 :(得分:0)
听起来您想要按VotedSong
然后按votes
(拼写错误为title
)对数组中的titel
个对象进行排序。如果是这样,这可能有效:
usort($votedsongs, function ($a, $b) {
if ($b->votes == $a->votes) {
return ($a->title < $b->title) ? -1 : 1;
}
return $b->votes - $a->votes;
});
答案 1 :(得分:0)
感谢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;
});