我需要计算第一列的值。我收到的任何给定的.csv文件中可能存在这些ID,也可能不存在。所以我需要循环查看第一列的.csv文件,如果它不存在则将其添加到保持数组($ PWSs),或者如果我已经添加了它,则增加该保持数组中的计数。 / p>
我有第一个循环使用fgetcsv()..这适用于破解文件:
$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。我需要数数。
"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"
答案 0 :(得分:2)
$fh = fopen('file.csv', 'rb');
$PWS = array();
while($row = fgetcsv($fh)) {
$PWS[$row[0]]++;
}
基本上它会使用第一列值作为键来填充PWS,并在它们出现时递增它们。之后,鉴于上面的示例csv,您最终会得到
$PWS = array(
'00513' => 4
'00154' => 1
'95343' => 1
'94585' => 1
etc...
);
答案 1 :(得分:1)
function get_pws()
{
$PWSs = array();
$handle2 = fopen ($uploadfileandpath,"r");
while ($field2array = fgetcsv ($handle2, 130000, ","))
{
if(!in_array($field2array[0], $PWSs))
{
array_push($PWSs, array('key'=>$field2array[0], 'count'=>1));
}
else
{
foreach($PWSs as &$PWS)
{
if($PWS['key'] == $field2array[0])
{
++$PWS['count'];
}
}
}
}
return $PWSs;
}
我实际上并没有运行并测试过这个脚本,所以希望它能够正常工作,这就是你要找的东西;)
编辑:感谢您指出dq。同样,我还没有测试过它(不是在安装了PHP的机器上),所以希望它仍然有用(如果它起作用的话):P
答案 2 :(得分:0)
您只需要一个 while 循环。你的外部while循环会在它到达eof时停止,因为fgetcsv()将返回FALSE。
然后只测试列为NULL或“”为空字符串。如果给定数组中不存在该列,则应使用 isset()以确保它在条件中首先存在。