我有两个Excel文件:
test1.csv
ID Name Price
Q1 Quail 100
Q2 Quail 200
Q3 Quail 300
test2.csv
ID Name Price
Q1 Quail 100
Q4 Quail 400
Q2 Quail 500
我想合并这些文件,因此,如果两个文件中都存在相同的ID,它将使用test2.csv中的日期。其余的IDS将从存在的文件中获取数据。我为此编写了代码,效果很好。
function combine($csvs){
if (empty($csvs[0])) {die ("please specify main csv file as a parameter\n");}
// combine csv files from parallel processes while skipping duplicates
$ls = $csvs;
if (!empty($ls)) {
print "CSV files to be processed:\n";
print_r($ls);
$visited = array();
$csvout = fopen("combined.csv", "w");
$wrote_header = false;
$cnt = 0;
foreach ($ls as $csv) { // foreach file from an extraction process
$csv = trim($csv);
print "combinig $csv\n";
$csvfp = fopen ($csv, "r");
$head = fgetcsv ($csvfp); // skipping header
if (empty($wrote_header)) {
fputcsv($csvout, $head);
$wrote_header = true;
}
while ($row = fgetcsv ($csvfp)) {
$sku = $row[0];print_r($sku);
if (empty($sku)) $sku = $row[1];
if (empty($visited[$sku])) fputcsv($csvout, $row);
$visited[$sku] = 1;
$cnt++;
if ($cnt%5000 == 0) print "processed $cnt products, saved ".count($visited)." products\n";
}
fclose ($csvfp);
}
print "saved ".count($visited). " records\n";
unset ($visited);
#$command = "rm -f {$csv_file}_*";
#print $command."\n";
#exec ($command);
fclose($csvout);
} else print "no csv file";
}
我这样称呼这个函数:
$csvs = array('test2.csv','test1.csv');
combine($csvs);
这就是我得到的结果:
combined.csv
ID Name Price
Q1 Quail 100
Q4 Quail 400
Q2 Quail 500
Q3 Quail 300
那很好。但是,我想在我的代码中为两个文件中都存在的IDS添加一些额外条件。
如果test2.csv中的价格比test1.csv中的价格大20%,则取test1.csv中的价格
任何帮助,我该怎么做?