我有許多行數相同的 CSV 檔案,例如以下
name age
Tom 18
John 16
Crisp 22
countries
The United States
Britain
Japan
professional
engineer
accountant
painter
現在我想將它們組合成一個單獨的 CSV,看起來像這樣
name age country professional
Tom 18 The United States engineer
John 16 Britain accountant
Crisp 22 Japan painter
也許我有更多的CSV檔案,我需要將它們合成為一個CSV檔案我該怎么辦?讀取 CSV 檔案的每一行,然后將其寫回?請提供任何幫助
uj5u.com熱心網友回復:
如果檔案不是太大,最簡單的解決方案是將所有資料存盤到一個全域陣列中,并在讀取所有資料時輸出:
$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);
輸出 :
name age countries professional
Tom 18 "The United States" engineer
John 16 Britain accountant
Crisp 22 Japan painter
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417060.html
標籤:
上一篇:根據名稱過濾CSV檔案并在RShiny上更新selectizeInput
下一篇:如何按月份分組為縮寫月份名稱
