计算匹配的数组值

计算匹配的数组值

问题描述:

I'm currently developing a PHP leaderboard, which lists the most popular/matching locations in descending order (High to Low).

I'm able to display the locations, but unable to group/match the locations and display in the high to low order.

Could somebody please advice on how todo this, thank you.

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("
", $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:

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
)

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

You can use array_count_values ( $array )

$your_result =  array_count_values($your_array);

var_dump($your_result);

You can use array_count_values() to get the occurrences and with this information sort the values in the way you want to.