[英]PHP: Merge 2 columns in all CSV file rows
Successful code will成功的代码将
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.