PHP阵列模式功能
以下模式函数将从值数组(也称为模式)中返回最常出现的值。如果仅使用数组,则仅返回最常出现的值。第二个参数可用于返回包含模式和该值在数组中出现的次数的数组。
function array_mode($array,$justMode=0) 
{
  $count = array();
  foreach ( $array as $item) {
    if ( isset($count[$item]) ) {
      $count[$item]++;
    }else{
      $count[$item] = 1;
    };
  };
  $mostcommon = '';
  $iter = 0;
  foreach ( $count as $k => $v ) {
    if ( $v > $iter ) {
    $mostcommon = $k;
    $iter = $v;
    };
  };
  if ( $justMode==0 ) {
    return $mostcommon;
  } else {
    return array("mode" => $mostcommon, "count" => $iter);
  }
}以下列方式使用。
$array = array(1,1,0,1); print_r(array_mode($array, 0)); //版画1 print_r(array_mode($array, 1)); // prints Array ( [mode] => 1 [count] => 3 )
如果您只想列出数组中最常见的值,则可以使用PHP函数array_count_values()。这将返回一个数组,其中包含该数组中的所有值以及每个值出现的次数。这是一个用法示例。
$array = array(1, 1, 0, 1); print_r(array_count_values($array)); // prints Array ( [1] => 3 [0] => 1 )