PHP中数组值的排名/位置 [英] Ranking/Position on value of array in PHP
本文介绍了PHP中数组值的排名/位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有这些值的数组, Array([0] => 12 [1] => 17 [2] => 5 [3] => 27 [4] => 5)
,我需要找出每个值
的排名/位置,即
I have an array with these values, Array ( [0] => 12 [1] => 17 [2] => 5 [3] => 27 [4] => 5 )
and I need to find out ranking/position of each value
ie,
for 27 - Rank 1
for 17 - Rank 2
for 12 - Rank 3
for 5 - Rank 4
for 5 - Rank 4 (duplicate value in the array)
这些必须与数组顺序相同,因此输出应为
and these need to be in the same order as the array, so that output should be as follow
12 - Rank 3
17 - Rank 2
5 - Rank 4
27 - Rank 1
5 - Rank 4
推荐答案
这应该起作用(包括具有相同等级的重复值):
This should work (including duplicate values having the same rank):
$values = array();
$values[0] = 5;
$values[1] = 12;
$values[2] = 19;
$values[3] = 9;
$values[4] = 5;
$ordered_values = $values;
rsort($ordered_values);
foreach ($values as $key => $value) {
foreach ($ordered_values as $ordered_key => $ordered_value) {
if ($value === $ordered_value) {
$key = $ordered_key;
break;
}
}
echo $value . '- Rank: ' . ((int) $key + 1) . '<br/>';
}
这篇关于PHP中数组值的排名/位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文