我需要在 csv 列中获取值的计数(分组)

2021-12-30 00:00:00 csv arrays grouping count php

我需要计算第一列的值.这些 ID 可能存在也可能不存在于我收到的任何给定的 .csv 文件中.因此,我需要遍历 .csv 文件,查看第一列,如果它不存在,则将其添加到一个保存数组 ($PWSs) 中,或者如果我已经添加了它,则增加该保存数组中的计数.

I need to get a count of the first column's values. These ID's might or might not exist in any given .csv file I receive. So I need to loop through the .csv file looking at the first column and either adding it to a holding array ($PWSs) if it doesn't exist or incrementing the count in this holding array if I've already added it.

我有第一个循环使用 fgetcsv()..这适用于破解文件:

I have the first loop using fgetcsv()..this works for cracking into the file:

$PWSs = array();

$handle2 = fopen ($uploadfileandpath,"r");
while ($field2array = fgetcsv ($handle2, 130000, ",")) 
{
    // Here is where I would add value or increment $PWSs array
    while (?)
    {
        if ($field2array[0] != ?)
        {
            // Add or increment
        }
    }
}

这是实际数据.第一列包含公共供水系统的 ID.我需要数一下.

Here is actual data. The first column has IDs for Public Water Systems. I need to count them.

"00513","08/13/2009","090834311A","R","4","OR1000x6","N","N","E",,1,".73","COLILERT"
"00513","08/13/2009","090834312A","R","39","OR1000x6","N","N","E",,1,".35","COLILERT"
"00154","08/13/2009","090835401A","R","300 Falls Road","OR100016","N","N","E",,1,".10","COLILERT"
"95343","08/13/2009","090835601A","R","Room 1 Sink","OR1000x6","N","N","E",,1,,"COLILERT"
"94585","08/14/2009","090837701A","R","Kitchen","OR1000x6","N","N","E",,1,,"COLILERT"
"94704","08/14/2009","090837801A","R","Outside Tap","OR1000x6","N","N","E",,1,,"COLILERT"
"01430","08/14/2009","090838201A","R","100 Deer Park Ln OT","OR1000x6","N","N","E",,1,,"COLILERT"
"00625","08/14/2009","090839001A","R","Dano and N Rose","OR100016","N","N","E",,1,".35","COLILERT"
"00405","08/17/2009","090840301A","R","Westmont Drive","OR100016","N","N","E",,1,".28","COLILERT"
"01031","08/17/2009","090840401A","R","Unit 2 Faucet","OR100016","N","N","E",,1,,"COLILERT"
"00625","08/17/2009","090840601A","R","Luman Road","OR1000x6","N","N","E",,1,".35","COLILERT"
"00513","08/17/2009","090841001A","R","40","OR1000x6","N","N","E",,1,".18","COLILERT"
"00513","08/17/2009","090841002A","R","10","OR1000x6","N","N","E",,1,".16","COLILERT"

推荐答案

$fh = fopen('file.csv', 'rb');

$PWS = array();
while($row = fgetcsv($fh)) {
    $PWS[$row[0]]++;
}

基本上,它将使用第一列值作为键来填充 PWS,并在它们出现时递增它们.之后,根据上面的示例 csv,您最终会得到

Basically it'll populate the PWS using the first column values as keys, and increment them as they come along. Afterwards, given your sample csv above, you'd end up with

$PWS = array(
    '00513' => 4
    '00154' => 1
    '95343' => 1
    '94585' => 1
etc...
);

相关文章