簡體   English   中英

過濾列並在PHP中轉換CSV

[英]Filter column and convert CSV in PHP

我想過濾一個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);
$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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM