Pergunta

I want to filter a csv file and add a condition then get the conversion.

My question is where i need to place the filter to convert the right data?

Condition ( if Value from Column 1 is not equal to Option 1 )

The file_data.csv (tabbed) file:

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

The php file to do the conversion:

$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);
Foi útil?

Solução

$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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top