这是针对一系列球员排名的抢七局。因此,忽略分数的总和,它们将是相同的(在此示例中为1400)。
所以,给定以下数组:
array(2) {
array(3) {
[0] => array(1) {
["score"] => 500
}
[1] => array(1) {
["score"] => 500
}
[2] => array(1) {
["score"] => 400
}
}
array(4) {
[0] => array(1) {
["score"] => 600
}
[1] => array(1) {
["score"] => 600
}
[2] => array(1) {
["score"] => 100
}
[3] => array(1) {
["score"] => 100
}
}
}
我想对其进行排序,以便具有最高个人得分(或最高得分数)的子阵列出现在最前面。如果这样可以打成平局,那么我们可以达到他们的第二高分等等。
E.g。在上面的示例中,600,600,100,100
优于500,500,400
,即使它们总共为1400。
同样0,100,300,300
会优于300,200,200,0,0
0,100,100,50
会比100,100,25,0,0,25
等更好。
这是迄今为止我提出的最好的,对我来说似乎非常混乱,我觉得必须有更好/更清洁的选择:
function sortTies($a, $b)
{
// get arrays of the scores and their counts
// each array item will have the score as the key and a count as the value
$aa = array_count_values(array_column($a, 'score'));
$bb = array_count_values(array_column($b, 'score'));
// sort them so that the highest scores are first
krsort($aa);
krsort($bb);
// get the length of the longest array
$maxLength = max(count($aa), count($bb));
// now we loop through, comparing the $i'th index of $aa to that of $bb
for($i = 0; $i < $maxLength; $i++) {
reset($aa);
reset($bb);
// move $i items deeper into the arrays
for($n=0; $n < $i; $n++) {
next($aa);
next($bb);
}
// if the keys differ at a certain position, we have our sort criteria, so should return...
if (key($aa) !== key($bb)) {
return key($bb) <=> key($aa)
}
// ...otherwise, we check the value stored under those keys in each array
elseif (current($aa) !== current($bb)) {
return current($bb) <=> current($aa);
}
// if the key and the value are the same, we don't return and we carry on into the next
// iteration of the loop, going one element deeper in each array
}
return 0; //dead heat
}
我可以做些什么来改善它?
答案 0 :(得分:1)
循环浏览列表,按分数分组,总和数量(分数实例)。 按分数排序desc。得到一个因子得分*数量,然后构建一个包含因子和列表的数组。 最后,按因子排序desc。
像这样:
<?php
$data=array(
array(
array(
"score" => 500
),
array(
"score" => 500
),
array(
"score" => 400
)
),
array(
array(
"score" => 600
),
array(
"score" => 600
),
array(
"score" => 100
),
array(
"score" => 100
)
)
);
$result = array();
foreach( $data as $i => $list ) {
$group = array();
foreach( $list as $index => $item ) {
if ( empty( $group ) ) {
$group[$item["score"]] = 1;
} else {
if ( isset( $group[$item["score"]] ) ) {
$qty = $group[$item["score"]];
$qty = $qty + 1;
$group[$item["score"]] = $qty;
} else {
$group[$item["score"]] = 1;
} // end if isset score
} // end if then else empty
} // end foreach $list
if ( !empty( $group ) ) {
// Order by key, desc
krsort( $group );
// Get the factor
$key = key( $group );
$factor = $key * $group[$key];
// Push
$result[$factor] = $list;
} // end if group not empty
} // end foreach $data
krsort( $result );
print_r( $result );