假设我有一个简单的1D阵列,有10-20个条目.有些会重复,我怎样才能找出最常使用的条目?喜欢..
$code = Array("test" , "cat" , "test" , "this", "that", "then");
Run Code Online (Sandbox Code Playgroud)
我如何将"test"显示为最常用的条目?
$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));
Run Code Online (Sandbox Code Playgroud)
您可以使用array_count_values计算每个值的出现次数.
$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)
}
*/
Run Code Online (Sandbox Code Playgroud)
要获得最常出现的值,可以在数组上调用max,然后使用array_search访问(第一个)值.
$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"
*/
Run Code Online (Sandbox Code Playgroud)
如果您希望满足多个最常用的值,那么以下内容将起作用:
$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"
}
*/
Run Code Online (Sandbox Code Playgroud)