我需要PHP帮助将CSV文件打开到数组中,更改数据,然后用更改后的数据覆盖原始CSV文件


I need PHP help opening a CSV file into an array, altering the data, and then overwriting the original CSV file with the altered data

我需要从CSV文件中提取数据以用于报告。但是,导出软件无法以有用的格式导出它。使用PHP,我想获取一个CSV文件,其中包含以下数据:

'Time','Month And Year','Count'
'8 Hours','Apr 2011','127'
'6 Hours','Apr 2011','45'
'4 Hours','Apr 2011','23'
'2 Hours','Apr 2011','122'
'8 Hours','Dec 2010','29'
'6 Hours','Dec 2010','8'
'4 Hours','Dec 2010','1'
'2 Hours','Dec 2010','64'
etc...

把它变成这样:

Time,Dec 2010,Jan 2011,Feb 2011,Mar 2011,Apr 2011,May 2011
8 Hours,126,47,115,77,127,110
6 Hours,45,18,62,38,42,31
4 Hours,23,3,11,8,15,18
2 Hours,122,93,185,144,128,70

目前,我有代码可以使用fgetcsv()打开CSV文件并删除不需要的字符:

$lines = array();
$tempName = array();
$tempCount = array();
$tempTitle = array();
$items = array();
$fp = fopen('../data/data2.csv','r') or die("can't open data2.csv");
while($lines = fgetcsv($fp,4096,"''n")) {
  for ($i = 0, $j = count($lines); $i < $j; $i++) {
    $lines[$i] = str_replace('''', '', $lines[$i]);
    $lines[$i] = str_replace('A: ', '', $lines[$i]);
    $lines[$i] = str_replace('B: ', '', $lines[$i]);
    $lines[$i] = str_replace('C: ', '', $lines[$i]);
    $lines[$i] = str_replace('D: ', '', $lines[$i]);
  }
}
fclose($fp) or die("can't close volume2.csv");

这将CSV文件的行存储到逗号分隔的行中,这使得$lines数组看起来像:

Time,Month And Year,Count
8 Hours,Apr 2011,127
6 Hours,Apr 2011,45
4 Hours,Apr 2011,23
2 Hours,Apr 2011,122
8 Hours,Dec 2010,29
6 Hours,Dec 2010,8
4 Hours,Dec 2010,1
2 Hours,Dec 2010,64
etc...

现在我需要做的是将数据以正确的顺序存储在一个或多个数组中,以便能够将其导出回CSV文件。

我尝试使用:

for ($h = 0, $k = count($lines); $h < $k; $h++) {
  $items = preg_split("/[,]+/",$lines[$h]);
}

然后使用case语句将正确的数据放入数组中,但它挂断了,所以我一定做错了什么。(更不用说这个代码没有优化。)

有什么想法吗?谢谢

您使用fgetcsv()的方式不对,并且一次读取多行。

修改您的代码以使用:

while($line = fgetcsv($fp)) {
}

并且在每次迭代中一次解析一行。

如果你想把它写回CSV文件,你应该能够做一些类似的事情:

$out = array();
while($line = fgetcsv($fp)) {
    // modify fields as you need to
    $out[] = implode(",", $line);
}
// now you can write implode("'n", $out) out as the modified data