Home > database >  Combine/move one column from CSV to another CSV as last column
Combine/move one column from CSV to another CSV as last column

Time:10-27

I'm having two CSV files. The first one contains two columns (comma separated) the second one contains just one column.

I'm trying to combine them and move the column from the second file as a last column to the first file.

The problem: when I run the script the column goes to the first file but instead of append as last column it completely replace the content of the file.

file_1.csv

1,13414214
6,13414214
13,13
3,33129

file_2.csv

title_1
title_2
title_3
title_4

When combined the file_1.csv should looks like

1,13414214,title_1
6,13414214,title_2
13,13,title_3
3,33129,title_4

The files are with same line numbers.

This is what I have so far

$file = fopen("file_1.csv","w");
$row = 1;
if (($handle = fopen("file_2.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000)) !== FALSE) {
        $num = count($data);
        $row  ;
        echo $data[0]. "\n";
        fputcsv($file, $data);
    }
}
fclose($handle);
fclose($file);

Any help is appreciated.

UPDATE: This is the output from the answer

1,13414214
,title_1

6,13414214
,title_2

13,13
,title_3

3,33129
,title_4

CodePudding user response:

For simplicity I would not try to attempt to write to file_1. Just read from file_1 and file_2 and then write to file_3. Something like:

$file1 = file("file_1.csv");
$file2 = file("file_2.csv");
$lines3 = [];
foreach ($file1 as $line1No => $line1) {
    $line2 = $file2[$line1No] ?? "";
    $lines3[] = trim($line1) . "," . trim($line2);
}
file_put_contents("file_3.csv", implode(PHP_EOL, $lines3));

As you can see, I treat the files as simple text file, not as CVS file, because I don't need to do anything with the data in them.

Note that this will only work somewhat when file_1.csv and file_2.csv contain the same number of lines.

Oh, and also: This might not be the best approach for very large files. Then it would probably be better, albeit a lot slower, to read them line by line.

  • Related