使用PHP解析csv数据以显示具有唯一列的行

时间:2017-07-16 01:24:00

标签: php csv

目标是处理csv文件中特定列中具有唯一数据的行列表。它应该只列出按顺序调用的前5个原因以及每个调用的总实例数。

数据示例:

userid | reason_for_call

abc1 |打印问题

abc2 |互联网问题

abc3 |电子邮件问题

abc8 |电子邮件问题

abc1 |打印问题

abc4 |打印问题

abc7 |电子邮件问题

abc4 |电子邮件问题

abc6 |扫描问题

abc1 |扫描问题

abc6 |传真问题

解析时,它应显示如下内容:

五大理由:
电子邮件问题(4个电话)
打印问题(3个电话)
扫描问题(2个电话)
传真问题(1个电话)
互联网问题(1个电话)

1 个答案:

答案 0 :(得分:1)

您应该将所有reasons_for_call收集到一个数组中并使用array_count_values()并从那里开始。

<?php

$reasons = [];

//Collect all of the call reasons.
if (($handle = fopen("data.csv", "r")) !== FALSE) {
    fgetcsv($handle, 10000, ","); //Skip first row.
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $reasons[] = $data[1];
    }
    fclose($handle);
}

//Count each of the values and sort the array by the value.
$values = array_count_values($reasons);
arsort($values);

//Get the first 5 elements in the array, and output as desired.
foreach(array_slice($values, 0, 5) as $reason => $count){
    echo $reason . " (" . $count . " calls)\n";
}

输入:

userid,reason_for_call
abc1,Issues with printing
abc2,Issues with internet
abc3,Issues with email
abc8,Issues with email
abc1,Issues with printing
abc4,Issues with printing
abc7,Issues with email
abc4,Issues with email
abc6,Issues with scanning
abc1,Issues with scanning
abc6,Issues with faxing

输出:

Issues with email (4 calls)
Issues with printing (3 calls)
Issues with scanning (2 calls)
Issues with internet (1 calls)
Issues with faxing (1 calls)
相关问题