简体   繁体   English

PHP:合并所有 CSV 文件行中的 2 列

[英]PHP: Merge 2 columns in all CSV file rows

Successful code will成功的代码将

  • open the csv file打开 csv 文件
  • merge the contents of 2 fields合并2个字段的内容
  • put those merged values into another existing field将这些合并值放入另一个现有字段
  • create new csv file with merged fields使用合并字段创建新的 csv 文件

Example starting CSV file:启动 CSV 文件的示例:

product_name,producttype,size,category,sub_category产品名称、产品类型、尺寸、类别、子类别

Lite 1/2 keg,Beer,1/2 keg,,pilsner Lite 1/2 桶,啤酒,1/2 桶,,比尔森啤酒

Bud Light 1/2 keg,Beer,1/2 keg,,pilsner Bud Light 1/2 桶,啤酒,1/2 桶,,比尔森

Expected ending CSV file:预期结束 CSV 文件:

product_name,producttype,size,category,sub_category产品名称、产品类型、尺寸、类别、子类别

Lite 1/2 keg,Beer,1/2 keg,Beer;1/2 keg;pilser,pilsner Lite 1/2 桶,啤酒,1/2 桶,啤酒;1/2 桶;pilser,pilsner

Bud Light 1/2 keg,Beer,1/2 keg,Beer;1/2 keg;pilser,pilsner Bud Light 1/2 桶,啤酒,1/2 桶,啤酒;1/2 桶;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>"; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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