PHP:比较2个csv文件中的1列,并将不匹配的行写入新文件
I have a products csv file containing both updates to current products and new products to be imported. I would like to filter out all existing products from the update file because I need to run the imports and updates separately. I have a second csv with all current products.
I would like to compare them based on the sku field which is the first field in both files and write any rows that don't exist in both files to a new csv so I can run my import without worrying about over-writing any data in my current products.
I am somewhat of a beginner with PHP so specifics and code examples are definitely appreciated!
我有一个产品csv文件,其中包含当前产品的更新和要导入的新产品。 我想从更新文件中筛选出所有现有产品,因为我需要单独运行导入和更新。 我有第二个csv与所有当前产品。 p>
我想基于sku字段比较它们,这是两个文件中的第一个字段,并将两个文件中不存在的任何行写入新的csv,这样我就可以运行了 我的导入而不用担心在我当前的产品中覆盖任何数据。 p>
我有点像PHP的初学者,所以特别感谢细节和代码示例! p>
I'm going to make some assumptions here ... you will have to adapt the solution to work for you.
I'm assuming that the second field in the csv file is something that when compared file over file will indicate that the product was updated, something like a last updated timestamp.
$prodFile = fopen("current-products.csv", "r");
// build a list of all of the sku's in prodFile
$prods = array();
while ($rec = fgetcsv($prodFile)){
// I am assuming the second field is an updated timestamp
$prods[$rec[0]] = $rec[1];
}
fclose($prodFile);
$newProdFile = fopen("new-products.csv", "r");
$addFile = fopen("productsToAdd.csv", "w");
$updateFile = fopen("productsToUpdate.csv", "w");
while ($rec = fgetcsv($newProdFile)){
if (!array_key_exists($rec[0], $prods)){
fputcsv($addFile, $rec);
}
if (array_key_exists($rec[0], $prods) &&
$prods[$rec[0]] != $rec[1]){
fputcsv($updateFile, $rec);
}
}
fclose($newProductFile);
fclose($addFile);
fclose($updateFile);