Reputation: 97
I need to compare two csv files. A new one that i get daily with new products and a second one that contains all products in stock. I have tool if therer are the same products in both files by comparing the sku. The first csv with the new products may have the same sku several times. So if there is a match than i need to add the Prod.ID from the second csv to the sku from the first csv in a new column.
This is how the first csv looks like:
ID SKU Cat Price
0 12345678 Clothes 10.00
0 12345678 Clothes 10.00
0 87654321 Bath 5.00
The second file lookes like this
ID SKU Cat Price
321 12345678 Clothes 10.00
532 87654321 Bath 5.00
So i need to add the ID from the second csv to every matching SKU in the first csv and save it to a verry new csv to get ist in the end look like this:
ID SKU Cat Price
321 12345678 Clothes 10.00
321 12345678 Clothes 10.00
532 87654321 Bath 5.00
Right now i have the following code, but i get only a empty updated.csv. I stuck totaly :(
$fp = fopen('updated.csv', 'w');
$csvFile1 = "firts-file.csv";
$handle1 = fopen($csvFile1, "r");
$csvFile2 = "second-file.csv";
$handle2 = fopen($csvFile2, "r");
while(($data1 = fgetcsv($handle, 20000, ";")) && ($data2 = fgetcsv($handle2, 20000, ";" ))) {
$oldID = $data1[0];
$newID = $data2[0];
if(($data1[1]) == ($data2[1])) {
fputs($fp, str_replace($oldID, $newID, "\n"));
}
}
Upvotes: 0
Views: 1756
Reputation: 126
1.csv - $result
ID SKU Cat Price
0 12345678 Clothes 10.00
0 12345678 Clothes 10.00
0 87654321 Bath 5.00
2.csv - $source
ID SKU Cat Price
321 12345678 Clothes 10.00
532 87654321 Bath 5.00
Code
<?php
$csvHandleOne = fopen('1.csv', "r");
$source = $result = array();
while($data = fgetcsv($csvHandleOne, 2048, ";")) {
$result[] = $data;
}
fclose($csvHandleOne);
$csvHandleTwo = fopen('2.csv', "r");
while($data = fgetcsv($csvHandleTwo, 2048, ";")) {
//We are interested only in SKU and ID link
$source[$data[1]] = $data[0];
}
fclose($csvHandleTwo);
$csvHandleResult = fopen('result.csv', "w");
foreach ($result as $key => $value) {
if($key && isset($source[$value[1]])) {
//SKU => ID link found in source. Set id to $result
$value[0] = $source[$value[1]];
}
fputcsv($csvHandleResult, $value, ';');
}
fclose($csvHandleResult);
Upvotes: 1