计算匹配的数组值

时间:2016-08-30 14:54:56

标签: php arrays

我目前正在开发一个PHP排行榜,它按降序排列最常用/匹配的位置(从高到低)。

我可以显示位置,但无法对位置进行分组/匹配,并按从高到低的顺序显示。

有人可以就如何做到这一点提出建议,谢谢。

PHP:

function parse_csv($file, $options = null) {
  $delimiter = empty($options['delimiter']) ? "," : $options['delimiter'];
  $to_object = empty($options['to_object']) ? false : true;
  $str = file_get_contents($file);
  $lines = explode("\n", $str);
  $field_names = explode($delimiter, array_shift($lines));
  foreach ($lines as $line) {
    if (empty($line)) continue;
    $fields = explode($delimiter, $line);
    $_res = $to_object ? new stdClass : array();
    foreach ($field_names as $key => $f) {
      if ($to_object) {
        $_res->{$f} = $fields[$key];
      } else {
        $_res[$f] = $fields[$key];
      }
    }
    $res[] = $_res;
  }
  return $res;
}
$arr_csv = parse_csv("/data.csv");
$array = array();
for ($i = 0; $i < count($arr_csv); ++$i) {
  array_push($array, $arr_csv[$i]["Location Name"]);
}
echo '<pre>';
print_r($array);
echo '</pre>';

阵列:

Array
(
    [0] => Bedford Sixth Form
    [1] => Tokko Youth Space
    [2] => WS Training
    [3] => WS Training
    [4] => University Technical College
    [5] => Bedford Academy
    [6] => Bedford College
    [7] => Bedford College
    [8] => Bedford College
    [9] => Bedford College
    [10] => Bedford College
    [11] => Bedford College
    [12] => Bedford College
    [13] => Bedford College
    [14] => Bedford College
    [15] => Bedford College
    [16] => Bedford College
    [17] => Bedford College
    [18] => Bedford College
    [19] => Bedford College
    [20] => Bedford College
)

3 个答案:

答案 0 :(得分:0)

您可以使用array_count_values($ array)

$your_result =  array_count_values($your_array);

var_dump($your_result);

答案 1 :(得分:0)

$array = array();
for ($i = 0; $i < count($arr_csv); ++$i) {
    if(!isset($array[$arr_csv[$i]["Location Name"]])){
        $array[$arr_csv[$i]["Location Name"]]=0;
    }
    $array[$arr_csv[$i]["Location Name"]]++;
}
asort($array);
$tmp=array();
foreach($array as $k=>$v){
   $tmp[]="$v. $k";
}
$array=$tmp;//or with array_reverse($tmp);

答案 2 :(得分:0)

您可以使用array_count_values()来获取事件,并使用此信息按您希望的方式对值进行排序。