我想合并3个csv文件,每个文件是:
File1.csv :
2014-01-01,10
2014-01-02,15
2014-01-03,25
.
.
.
File2.csv :
2014-01-01,20
2014-01-02,26
2014-01-03,46
.
.
.
File3.csv :
2014-01-01,30
2014-01-02,35
2014-01-03,40
.
.
.
我想合并到1个csv文件中,调用merge.csv:
2014-01-01,10,20,30
2014-01-02,15,26,35
2014-01-03,25,46,40
我试过这些:
但它仍然无效。我该怎么办?
答案 0 :(得分:1)
我认为应该这样做
$file1 = fopen('file1.csv', 'r');
$file2 = fopen('file2.csv', 'r');
...
$merged = fopen('merged.csv', 'w');
$files = array($file1,$file2,...);
$output=array();
foreach($files as $file){
while (($line = fgets($file)) !== false) {
list($index,$value)= explode(',',trim($line));
$output[$index][]=$value;
}
}
foreach($output as $key => $values){
fwrite($merged, $key . ',' . implode(',',$values).PHP_EOL);
}