-1

Successful code will

  • open the csv file
  • merge the contents of 2 fields
  • put those merged values into another existing field
  • create new csv file with merged fields

Example starting CSV file:

product_name,producttype,size,category,sub_category

Lite 1/2 keg,Beer,1/2 keg,,pilsner

Bud Light 1/2 keg,Beer,1/2 keg,,pilsner

Expected ending CSV file:

product_name,producttype,size,category,sub_category

Lite 1/2 keg,Beer,1/2 keg,Beer;1/2 keg;pilser,pilsner

Bud Light 1/2 keg,Beer,1/2 keg,Beer;1/2 keg;pilser,pilsner

kightn
  • 1
  • 1
  • https://stackoverflow.com/questions/36142899/add-2-new-column-header-and-contents-in-csv-file-using-php seems to be the closest think I could find here. – kightn May 03 '20 at 16:04
  • [link]https://stackoverflow.com/questions/28550794/add-data-to-csv-file-in-specific-columns-using-php led to solution. – kightn May 04 '20 at 19:58

1 Answers1

0

Here is the solution I found. Likely not the most elegant one.

<?php
//Brand_Name Brand_Description SKUNumber UPC product_type CATEGORY SUB-CATEGORY BEER TYPE BEER STYLE PRODUCER price_regular Size Web Active Quantity_Available
$columns = ["Brand_Name","Brand_Description","SKUNumber","UPC","product_type","CATEGORY","SUB-CATEGORY","BEER TYPE","BEER STYLE","PRODUCER","price_regular","Size","Web Active","Quantity_Available"];
//$columns = ["sku","category","description","image","small_image","thumbnail", "price","color"];

$file = fopen("Products_In.csv", "r"); //Open the old file for reading
$newFile = fopen("Products_Out.csv", "w"); //Create a new file for writing

while (($data = fgetcsv($file)) !== FALSE) {
    $row = array_combine($columns, $data);
    if(!empty($row['BEER TYPE'])){
     $category = "{$row['product_type']};{$row['Size']};{$row['BEER TYPE']}";
    } else {  
     $category = "{$row['product_type']};{$row['Size']}";
    }
 $row['SUB-CATEGORY'] = $category;
    fputcsv($newFile, array_values($row)); //write data into new file
}

fclose($file);
fclose($newFile);
echo "<h1>Categories updated</h1>";
?>
kightn
  • 1
  • 1