0

I am trying to write multiple rows to CSV file without using a loop. Actually, I have a single column SKU in my CSV file. I have an array of multiple SKUs.m I want to write those SKUs into CSV without using any loop. Can anyone know then please guide me?

I have looked this below thread but it is not what I require

How to Write Multiple Rows/Arrays to CSV File in one attempt using PHP?

Thanks

U.Malik
  • 111
  • 11
  • Have you thought about using the function `implode()`? You might do something like `$contentRows = implode("\n", $rows)`. (technically that is still a loop, but it will probably perform better than using foreach()) – Tobias F. Jan 31 '19 at 11:40
  • I have to ask why? Whats wrong with a loop?? – RiggsFolly Jan 31 '19 at 11:43
  • @TobiasF.I am going to try this. Can you please let me know how I will use it with fputcsv() function? Can I do this like fputcsv($file,$contentRows); ? – U.Malik Jan 31 '19 at 12:08
  • @RiggsFolly I know the loop way but I though there must be better way to write a csv file in single line of code. – U.Malik Jan 31 '19 at 12:09
  • @TobiasF. implode didn't work here. because fputcsv require array not a string. – U.Malik Jan 31 '19 at 12:14
  • I have tried to write array using fputcsv function and it put the each index value to different columns . seems it wokred for column wise not row wise – U.Malik Jan 31 '19 at 12:15

1 Answers1

1

Have you tried using the array_map function in PHP?

array_map(function($element){ fputcsv($file, [$element]) }, $sku_array);

This is a form of functional programming, that eschews traditional looping structures.

judges119
  • 36
  • 1
  • 3