php - PHP中如何对数组的索引进行排序

标签 php ranking

我需要在我的系统中排名。我有一个数组 $arr = array(120,26,38,96,22);。我需要对内部索引进行排名而不改变它们的位置。

我需要的输出是这样的:

120 is rank 1, 26 is rank 4, 38 is rank 3, 96 is rank 2, 22 is rank 5

我已经尝试过这个,但都排名第一:

<?php
$arr = array(120,26,38,96,22);
$rank = 0;
$score=false;
$rows = 0;

foreach($arr as $sort){
    $rows++;
    if($score != $arr){
        $score = $arr;
        $rank = $rows;
    }echo $sort.' is rank '.$rank.'</br>';  
}
?>

而且我还需要动态的数组长度。

最佳答案

这是一种方法:

$arr  = array(120,26,38,96,22);
$rank = $arr;
rsort($rank);

foreach($arr as $sort) {
    echo $sort. ' is rank ' . (array_search($sort, $rank) + 1) . '</br>';
}
  • 将原始数组复制为 $rank 并反向排序,因此键将为排名 -1
  • 循环原始数组并在 $rank 中搜索该值,返回键(排名)
  • 由于键从 0 开始所以加 1

或者另一种可能性:

$arr  = array(120,26,38,96,22);
$rank = $arr;
rsort($rank);
$rank = array_flip($rank);

foreach($arr as $sort) {
    echo $sort . ' is rank '. ($rank[$sort] + 1) . '</br>';
}
  • 将原始数组复制为 $rank 并反向排序,因此键将为排名 -1
  • 翻转 $rank 数组以获取值作为键,排名作为值
  • 循环原始数组并使用该值作为$rank键来获取排名
  • 由于键从 0 开始所以加 1

关于php - PHP中如何对数组的索引进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41617333/

相关文章:

php - mysql - 获胜排名没有平局

python - 如何根据另一列中的日期值范围创建排名列?

algorithm - 简单的排名算法

php - 如何在 Laravel 中定义虚假价格、地址、图片

php - Kohana 3.2 中的 $this->request->param() 和 $this->request->post()

php - 在 PHP 中执行 Curl 以进行 Stripe 订阅

php - 无法将 JSON 解码为 PHP 数组并显示在 HTML 表中

php - 如何从 PHP 生成的输出中获取漂亮的 HTML 源代码?

.net - LINQ中的“Most popular” GROUP BY?

php - Mysql + PHP for "Wilson Score Interval"with time gravity