I have many CSV files with the same number of lines, such as the following
name age
Tom 18
John 16
Crisp 22
countries
The United States
Britain
Japan
professional
engineer
accountant
painter
Now I want to combine them into a separate CSV that looks something like this
name age country professional
Tom 18 The United States engineer
John 16 Britain accountant
Crisp 22 Japan painter
Maybe I have more CSV files, and I need to synthesize them into a CSV file What should I do? Read each line of the CSV file and then write it back? Any help please
CodePudding user response:
It the files are not too big, the easiest solution is to store all the data into a global array and output it when all the data are read :
$delimiter = "\t" ;
$input_files = array('users.csv', 'countries.csv', 'professions.csv'); // files to merge
// read all the data, store them in $result
$result = array(); // final array with merged fields
foreach($input_files as $file)
{
$reader = fopen($file, 'r');
$line_index = 0 ;
while($line = fgetcsv($reader, null, $delimiter) )
{
if(! array_key_exists($line_index, $result)) // if the line doesn't exist in the result yet, create it
$result[$line_index] = array();
$result[$line_index] = array_merge($result[$line_index], $line) ; // append the current field to the existing line
$line_index;
}
fclose($reader);
}
// output the result
$writer = fopen('result.csv', 'w ');
foreach($result as $row)
{
fputcsv($writer, $row, $delimiter);
}
fclose($writer);
Output :
name age countries professional
Tom 18 "The United States" engineer
John 16 Britain accountant
Crisp 22 Japan painter
