如何获取php数组中的前3个值及其索引 [英] how to get top 3 values in php array and their index

查看:54
本文介绍了如何获取php数组中的前3个值及其索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得最高价值,第二最高价值和第三最高价值

I want to get the highest value, the second highest value and the third highest value

例如,我有一个类似的数组:

For example, I have an array like:

$ n = array(100,90,150,200,199,155,15,186);

我知道获取最大值及其索引的方法:

I know the method to get the max value and its index:

echo max($ n);//200$ maxs = array_keys($ n,max($ n));echo $ maxs [0];//3

我想获取前3个值及其索引,例如:value:200,199,186 index:3,4,7

I want to get the top 3 values and their index like : value: 200, 199, 186 index:3,4,7

我如何获得它们?

推荐答案

这应该可以解决问题:

function maxNitems($array, $n = 3){
    asort($array);
    return array_slice(array_reverse($array, true),0,$n, true);
}

使用方式:

maxNitems(array(100,90,150,200,199,155,15,186));

这篇关于如何获取php数组中的前3个值及其索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆