简体   繁体   中英

PHP: Merge 2 columns in all CSV file rows

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

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>"; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM