Adam Adam - 3 months ago 25
PHP Question

Count matching array values

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("\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:

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
)

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