PHP从数组获取多个最大值 [英] PHP Get multiple highest values from array

查看:727
本文介绍了PHP从数组获取多个最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,该脚本将一堆变量(在这种情况下为随机字母A到D)放入数组中,计算这些变量的频率,找到最高频率,然后找到与该频率匹配的键.

I have a script that puts a bunch of variables (in this case random letters A through D) into an array, counts the frequency of these variables, finds the highest frequency and then finds the key that matches this frequency.

$answerlist = array($a1, $a2, $a3, $a4,);
$count = array_count_values($answerlist);
$high_value = max($count);
$high_key = array_search($high_value, $count); 
print_r ($high_key);

但是,在存在2个相等的最大值的情况下,array_search仅返回第一个键.有办法将两者都退还吗?

However in a case where there are 2 equal highest values, array_search only returns the first key. Is there a way to return both?

推荐答案

这应该做到:

$high_keys = array_keys($count, $high_value);

来自 文档:

如果在干草堆中多次发现needle,则返回第一个匹配键.要返回所有匹配值的键,请使用array_keys()和可选的search_value参数.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

这篇关于PHP从数组获取多个最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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