PHP:如何找到最常用的数组键?
假设我有一个简单的1D数组,有10-20个条目。有些是重复的,我如何找出哪个条目使用最多?像PHP:如何找到最常用的数组键?,php,arrays,Php,Arrays,假设我有一个简单的1D数组,有10-20个条目。有些是重复的,我如何找出哪个条目使用最多?像 $code = Array("test" , "cat" , "test" , "this", "that", "then"); 如何将“test”显示为最常用的条目?$code=Array(“test”、“cat”、“test”、“this”、“that”、“then”); $code = Array("test" , "cat" , "test" , "this", "that", "then")
$code = Array("test" , "cat" , "test" , "this", "that", "then");
如何将“test”显示为最常用的条目?$code=Array(“test”、“cat”、“test”、“this”、“that”、“then”);
$code = Array("test" , "cat" , "test" , "this", "that", "then");
function array_most_common($input) {
$counted = array_count_values($input);
arsort($counted);
return(key($counted));
}
echo '<pre>';
print_r(array_most_common($code));
函数数组最常用($input){
$counted=数组计数值($input);
阿索特(已计);
返回(键($counted));
}
回声';
打印(数组最常用($code));
使用您可以通过使用获得每个值的出现次数计数 要获取最常出现的值,可以调用数组,然后使用访问(第一个)值 如果您希望满足多个最常见的值,那么以下类似的方法将起作用:
对整个数组进行排序只是为了找到最大值似乎有点浪费。@Thomas如果数组没有预先排序,有没有一种明显、更快的替代方法?不是争论,只是提问。@Thomas Sort将比数组上的线性循环更快。如果您愿意,您可以始终删除arsort()并执行for循环,以确定哪一个具有最高计数。@Pekka:Sort是O(n log n),您应该能够在O(n)时间内确定最大值。但是,也许PHP实现的
arsort
与您自己的for
循环相比,在实践中排序速度更快;我不知道。
$code = array("test" , "cat" , "cat", "test" , "this", "that", "then");
$counts = array_count_values($code);
var_dump($counts);
/*
array(5) {
["test"]=>
int(2)
["cat"]=>
int(2)
["this"]=>
int(1)
["that"]=>
int(1)
["then"]=>
int(1)
}
*/
$code = array("test" , "cat" , "cat", "test" , "this", "that", "then");
$counts = array_count_values($code);
$max = max($counts);
$top = array_search($max, $counts);
var_dump($max, $top);
/*
int(2)
string(4) "test"
*/
$code = array("test" , "cat" , "cat", "test" , "this", "that", "then");
$counts = array_count_values($code);
$max = max($counts);
$top = array_keys($counts, $max);
var_dump($max, $top);
/*
int(2)
array(2) {
[0]=>
string(4) "test"
[1]=>
string(3) "cat"
}
*/