简体   繁体   中英

How to merge new csv file as a new column into an existing csv file using php or even javascript

I have a few csv file with 1 column and multiple rows of data as follow:

file1.csv:
Monday
Adam
Andrew

file2.csv:
Tuesday
James
Sally
Sean
Ben
Sid

file3.csv:
Wednesday
Conny
Steve
Albert

How can I take the data from these 3 files and place them as separate column in a new csv file? I am using php and javasript and if any of this can do the job will be good.

I manage to get it to work base on a part of your codes above. First I need to get the data from each file into a simple array since they only have 1 column each. Then I count the rows in each file and get the max count like what you did. Finally I place the data from each file into the for loop like below:

for ($row_index = 0; $row_index < $row_count; $row_index++) {
$row = array($mondaycol[$row_index], $tuesdaycol[$row_index] , $wednesdaycol[$row_index], $thursdaycol[$row_index], $fridaycol[$row_index], $saturdaycol[$row_index], $sundaycol[$row_index]);


fputcsv($outFile, $row);

}

It may be possible to do this on the JS side using the File API .

It's definitely possible to do it on the PHP side. Here's related documentation on handling file uploads .

To read a CSV file, check out fgetcsv() . Use this to get the contents of each file into an array.

At that point, you should be able to do something like this:

<?php

// $file1 = ...
// $file2 = ...
// $file3 = ...

$rows = [];
$row_count = max(count($file1), count($file2), count($file3));
for ($row_index = 0; $row_index < $row_count; $row_index++) {
    $row = [];
    $row[0] = $file1[$row_index] ?? '';
    $row[1] = $file2[$row_index] ?? '';
    $row[2] = $file3[$row_index] ?? '';
    $rows[] = $row;
}

Once you've got the data you want to write to the new file into its own array (ie $rows in the above example), you can use fputcsv() to write it.

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