本文介绍了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中数组值的排名/位置
发布评论