PHP中数组值的排名/位置

编程入门 行业动态 更新时间:2024-10-06 06:45:51
本文介绍了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中数组值的排名/位置

本文发布于:2023-11-28 04:27:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   位置   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!