I have two CSV files. They have same number of columns but can have different rows. I just need to combine all 10 csv files into one master csv file such that the total number of rows add up.
File 1:
John Andy 10 20
Adam Sam 15 25
File 2:
Sam Eric 34 40
Ryan Rob 15 22
Final csv file:
John Andy 10 20
Adam Sam 15 25
Sam Eric 34 40
Ryan Rob 15 22
You can do this with str_getcsv()
( http://php.net/manual/en/function.str-getcsv.php )
$file1 = str_getcsv('my_file1.csv');
$file2 = str_getcsv('my_file2.csv');
Then combine the arrays:
$allfiles = $file1 + $file2 + $file3 [...]
$allfiles = array_merge($file1, $file2 [...])
array_merge()
will actually re-index them, just combining them ( $file1 + $file2
) will simply append them.
Here's the documentation on array_merge()
:
Finally, once you have your $allfiles
variable, you can output it via fputcsv()
:
http://php.net/manual/en/function.fputcsv.php
If your files are massive, you'll likely want a different solution. This will (unnecessarily) take up a large amount of memory by placing each file into a variable (then placing them all into one). The solution to that would be to use a pointer, where you'd never really load more than a line into memory at a time.
However, if your files are small, this may work just fine.
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.