过滤列并在PHP中转换CSV

时间:2013-10-24 14:11:22

标签: php csv option

我想过滤csv文件并添加条件然后获得转换。

我的问题是我需要放置过滤器以转换正确的数据吗?

条件(如果第1列的值不等于选项1)

file_data.csv(标签式)文件:

Group   Option  Data    Value
Group1  Option 1    DATA01  2
Group1  Option 1    DATA02  3
Group1  Option 1    DATA02 2
Group1  Option 1    DATA03  1
Group1  Option 1    DATA03  2
Group2  Option 2    DATA04  3
Group4  Option 4    DATA05  7

要进行转换的php文件:

$tsvFile = new SplFileObject('file_data.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('data', 'value');
fputcsv($file, $header, ',', '"');
$newData = array();
foreach ($tsvFile as $line => $row) {
    if($row[1] != 'Option 1'){ // + Here
    if ($line > 0) {
    //if($row[1] != 'Option 1'){ //-From here
    if (isset($newData[$row[2]])) {
            $newData[$row[2]]+= $row[3];
        } else {
            $newData[$row[2]] = $row[3];
            }
        }
    }
}
foreach ($newData as $key => $value) {
    fputcsv($file, array($key, $value), ',', '"');
}
fclose($file);

1 个答案:

答案 0 :(得分:0)

$tsvFile = new SplFileObject('file_data.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('data', 'value');
fputcsv($file, $header, ',', '"');
$newData = array();
foreach ($tsvFile as $line => $row) {
    if($row[1] != 'Option 1'){ // + Here
    if ($line > 0) {
    //if($row[1] != 'Option 1'){ //-From here
    if (isset($newData[$row[2]])) {
            $newData[$row[2]]+= $row[3];
        } else {
            $newData[$row[2]] = $row[3];
            }
        }
    }
}
foreach ($newData as $key => $value) {
    fputcsv($file, array($key, $value), ',', '"');
}
fclose($file);