PHP:如何查找最常用的数组键?

oni*_*kun 3 php arrays

假设我有一个简单的1D阵列,有10-20个条目.有些会重复,我怎样才能找出最常使用的条目?喜欢..

$code = Array("test" , "cat" , "test" , "this", "that", "then");
Run Code Online (Sandbox Code Playgroud)

我如何将"test"显示为最常用的条目?

Ivo*_*bev 9

$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)

  • @Pekka:Sort是O(_n_ log _n_),你应该能够在O(_n_)时间内确定最大值.但也许PHP的'arsort`的实现与滚动你自己的`for`循环使得在实践中排序更快; 我不知道. (3认同)
  • @Thomas有一个明显的,更快的替代方案,因为数组没有预先排序?不争论,只是问. (2认同)
  • @Thomas Sort比阵列上的线性循环更快.如果您希望可以随时删除arsort()并执行for循环以确定哪一个具有最高计数. (2认同)

sal*_*the 5

您可以使用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)