我有以下数组:
$learners=array('Eliza'=87, 'Joe'=81, 'Anne'=69, 'Marley'=39, 'Teddy'=39, 'Jemma'=90, 'Sylvia'=87);到目前为止,我已经能够将这两个数组分开如下:
$tudents=array_keys($learners);
$scores=array_values($learners);排名如下:
Student Score Position
Jemma 90 1
Sylvia 87 2
Eliza 87 2
Joe 81 4
Anne 69 5
Marley 39 7
Teddy 69 7我想要创建一个新数组,名称作为键,位置作为值,例如
$positions=array('Jemma'=1, 'Sylvia'=2, 'Eliza'=2, 'Joe'=4, 'Anne'=5, 'Marley'=7, 'Teddy'=7);这将使我能够在脚本上的任何点重复任何名称和位置。我不知道该如何进行。
如果分数有重复,排名就不那么简单了。如果2号有平局,则跳过第三个位置。如果领带发生在分数的末尾,那么两个分数都将放在最后一个位置,而前面的位置将被跳过,在上面的示例中,位置6被跳过,两个39s占据位置7。
如有任何帮助,将不胜感激。
发布于 2013-11-02 00:01:41
// Sort decending
arsort($data);
$vals = array_values($data);
$last = end($vals); // The lowest score
$prev = null;
$rank = 0;
$positions = array();
foreach($data as $student => $score) {
if ($score == $last) {
// The score is the same as the lowest, the rank is set to last position
$rank = count($data);
} else if ($prev != $score) {
// We only update if the score is not the same as prev
$rank++;
} else if ($prev == $score) {
// We matched on the key, replace any items with the
// same score with the current rank
$matches = array_keys($positions, $score);
foreach($matches as $key) {
$positions[$key] = $rank;
}
$positions[$student] = $rank;
// Now skip ahead to the next rank +1
$rank = $rank + count($matches) + 1;
continue;
}
$positions[$student] = $rank;
$prev = $score; // Remember the previous score
}
var_dump($positions);发布于 2013-11-01 23:30:15
以下是另一个解决方案:
第一个按值排序( print_r只是检查进度)。
arsort($learners);
print_r($learners);然后进行一系列的排名,但如果分数与前一个元素的得分相同,则不要提高排名。
$rank = $pos = 1;
$prev_score = current($learners);
foreach ($learners as $name => $score) {
if ($score != $prev_score) {
$rank = $pos;
}
$ranking[$name] = $rank;
$prev_score = $score;
$pos++;
}
print_r($ranking);现在更正最后一个条目,任何与最后一个元素得分相同的元素都应该排在第七位。array_keys()有一个很少使用的参数来搜索给定的值。
$low_score = end($learners);
$last_place = count($learners);
foreach (array_keys($learners, $low_score) as $name) {
$ranking[$name] = $last_place;
}
print_r($ranking);输出:
Array
(
[Jemma] => 90
[Sylvia] => 87
[Eliza] => 87
[Joe] => 81
[Anne] => 69
[Marley] => 39
[Teddy] => 39
)
Array
(
[Jemma] => 1
[Sylvia] => 2
[Eliza] => 2
[Joe] => 4
[Anne] => 5
[Marley] => 6
[Teddy] => 6
)
Array
(
[Jemma] => 1
[Sylvia] => 2
[Eliza] => 2
[Joe] => 4
[Anne] => 5
[Marley] => 7
[Teddy] => 7
)发布于 2013-11-01 22:58:12
看起来像PHP对吧?
基本上,先看一遍你的初始列表,然后把它们放入一个新数组中,用名字作为键(如果两个人的名字是相同的,那么这里就有麻烦了,但我假设这是一项家庭作业,这不是问题吗?)
$sorted = array();
for ($i=0;$i<count($positions);$i++) {
if (!isset($sorted[$positions[$i]["Student"]])) {
$sorted[$positions[$i]["Student"]] = $positions[$i]["Score"];
} else if ($sorted[$positions[$i]["Student"]]<$positions[$i]["Score"] {
$sorted[$positions[$i]["Student"]] = $positions[$i]["Score"];
}
}你在这里做的是做一个数组,其中的键是学生的名字,并把你找到的第一个分数作为这个值。所以$sorted"Jemma“= 90。然后,如果您再次按下这个名称,并且分数高于$sorted"Jemma“的当前值,您将替换它。
在此之后,您将运行一个ar排序($sorted)来对其进行排序。
https://stackoverflow.com/questions/19736690
复制相似问题