php - 数组中的数组

标签 php mysql

我有以下数组:

$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 位出现平局,则跳过第 3 位。如果平局出现在分数的末尾,那么两个分数将被放在最后一个位置,前面的位置将被跳过,在上面的例子中,位置 6 被跳过,两个 39 占据位置 7。

任何帮助将不胜感激

最佳答案

// 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);

关于php - 数组中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19736690/

相关文章:

mysql - 使 CMD 敏感以与 MySQL 一起使用?

MySQL UNION 查询即使使用 GROUP BY 也会返回重复值

使用 session 和重定向的 PHP 错误处理

php - 使用外键合并两个数据库时的 SQL 问题

php - 使用键从多维数组中获取值(复数)

php - 数据库

mysql - 如何在Excel中创建动态表格?

php - 为什么相同的 http 请求在浏览器中有效,但从我的 Android 应用程序发送时却失败了?

php - 将 ssh key 与 Composer 一起用于私有(private) vcs

php - MySQL 增加查看计数查询 - 非常慢