0

我有如下所示的 CSV 文件:

State, name, balans
OH, John, 345
OH, Bill, 281
IL, James, 34
OH, James, 45
MA, Bill, 71
OH, Thomas, 541 
SC, Pete, 125
AL, Mary, 51
NY, Ivan, 123
MD, Chan, 234
CA, Lee, 181
WI, Juan, 131
AL, Kate, 135
CO, Robert, 215

我需要按州汇总总余额。

因此,输出 file.txt 将如下所示:

OH [Sum of balans]   
NY [sum of ballans]
etc

我在互联网上寻找这样的例子,但没有找到任何东西。我需要一些代码示例或框架,我可以使用。

我想我应该做这样的事情:

$inputfile  = 'input.csv';

$outputFile = 'output.txt';


$inputHandle = fopen($inputfile, "r");
$outputHandle = fopen($outputFile, 'w');
$balansCol = 2;

while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {

    $sumArray = array();
    $sumArray[] = $dataRow;      
 }

   foreach ($sumArray as  $subArray) {

    foreach ($subArray as $id => $value) {
        $sumArray[2] += $value;
    }
}

但我认为这不是好方法......有人可以提供一些相对简单的方法来解决它吗?

4

2 回答 2

0

这是一种方法(经过测试,您必须修改输出)并且应该可以帮助您入门:

$csv = <<< ENDL
OH, John, 345
OH, Bill, 281
IL, James, 34
OH, James, 45
MA, Bill, 71
OH, Thomas, 541 
SC, Pete, 125
AL, Mary, 51
NY, Ivan, 123
MD, Chan, 234
CA, Lee, 181
WI, Juan, 131
AL, Kate, 135
CO, Robert, 215 
ENDL;

$csv = explode("\n", $csv); // using this instead of file("file.csv");
$output = array();
foreach($csv as $line) {
    list($state, $name, $count) = str_getcsv($line);
    $state = trim($state);
    $name  = trim($name);
    $count = trim($count);
    $output[$state] += (int)$count;
}

echo "<pre>";
var_dump($output);
/**
Outputs:
array(10) {
  ["OH"]=>
  int(0)
  ["IL"]=>
  int(0)
  ["MA"]=>
  int(0)
  ["SC"]=>
  int(0)
  ["AL"]=>
  int(0)
  ["NY"]=>
  int(0)
  ["MD"]=>
  int(0)
  ["CA"]=>
  int(0)
  ["WI"]=>
  int(0)
  ["CO"]=>
  int(0)
}
**/

PS:可能不是海量文件的最佳解决方案。

于 2013-07-01T21:17:41.080 回答
0

不需要子数组和不止一次的迭代。为总和创建空数组并在循环文件时填充它创建/添加元素:

$sumArray = array();
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
    $state = $dataRow[0];
    $balance =  $dataRow[2];
    if (!isset($sumArray[$state])) {
        $sumArray[$state] = 0; // create new entry for state with balance=0
    }
    $sumArray[$state] += $balance; // add balance for state
}
于 2013-07-01T21:22:39.970 回答