从平面数组中获取 N 个最高分,并在出现平局时允许每个合格分数包含无限个元素
我正在开发一个排行榜,根据分数将得分最高的选手分为第一、第二和第三位。现在我正在使用一个看起来像这样的排序数组(但可能具有无限长度和无限点值):
$scores = Array
(
["bob"] => 20
["Jane"] => 20
["Jill"] => 15
["John"] => 10
["Jacob"] => 5
)
我想我可以使用一个简单的切片或块,但我想允许关系,并忽略任何不属于前三名的点,如下所示:
$first = Array
(
["bob"] => 20
["Jane"] => 20
)
$second = Array
(
["Jill"] => 15
)
$third = Array
(
["John"] => 10
)
I'm working on a leader board that pulls the top scorers into first, second, and third place based on points. Right now I'm working with a sorted array that looks like this (but could be of infinite length with infinite point values):
$scores = Array
(
["bob"] => 20
["Jane"] => 20
["Jill"] => 15
["John"] => 10
["Jacob"] => 5
)
I imagine I could use a simple slice or chunk, but I'd like to allow for ties, and ignore any points that don't fit into the top three places, like so:
$first = Array
(
["bob"] => 20
["Jane"] => 20
)
$second = Array
(
["Jill"] => 15
)
$third = Array
(
["John"] => 10
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
$first 将在 $output[0] 中,$second 将在 $output[1] 中,依此类推。代码仅限于 3 个第一位置。
ps:更新处理第三名的平局
$first will be in $output[0], $second in $output[1] and so on.. Code is limited to 3 first places.
ps: updated to deal with tie on the third place
我会做类似的事情:
它对数组进行排序,然后创建编号组。一旦达到极限,它就会中断。
如果您使用分数作为数组的键,则可以使用更少的代码来完成此操作,但上述方法的好处是它可以在第一次时完全按照您想要的方式创建数组。
如果您不介意对原始内容进行排序,您也可以通过引用传递
$scores
。I would do something like:
It sorts the array, then creates numbered groups. It breaks as soon as the limit has been reached.
You can do it with less code if you use the score as the key of the array, but the benefit of the above approach is it creates the array exactly how you want it the first time through.
You could also pass
$scores
by reference if you don't mind the original getting sorted.这是我的做法:
Here's my go at it:
按分数排序,然后筛选和分组:演示
筛选和分组,然后按分数组排序:演示
如果您的输入数组已按分数降序排序,则可以省略这些脚本中的排序调用。
Sort by score then filter and group: Demo
Filter and group then sort by score group: Demo
If your input array is already sorted with descending scores, you can omit the sorting calls in these scripts.