如何在PHP中逐行合并CSV文件 [英] How to Merge CSV Files in PHP, Line by Line

查看:356
本文介绍了如何在PHP中逐行合并CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在PHP中合并几个CSV文件在一起。我已经将它们合并为整个文件使用PHP感谢这里的线程(组合2个CSV文件 ),但我正在寻找合并文件在一起的个别行。

I am trying to merge several CSV files together in PHP. I already have them merged as whole files using PHP thanks to the thread here (Combining 2 CSV files), however I am looking to merge the files together by individual line.

我想从 CSV 1 中读取第1行,从 CSV 2第1行等等,然后继续第2,3行等。 - 在每个循环的数组中的文件之间循环。我没有在PHP中解析文件,所以我不知道从哪里开始完成这个。

I would like to read line 1 from CSV 1, line 1 from CSV 2, and so forth, then proceed to line 2, 3, etc. - Cycling between the files in the array with each loop. I have not worked with parsing files in PHP much, so I'm not sure where to begin to accomplish this.

这是我想要完成的,万一以上不明确:

This is what I am trying to accomplish, in case the above was not clear:


CSV1 - 第1行

CSV1 - Line 1

CSV2 1

CSV3 - 第1行

CSV3 - Line 1

CSV1 - 第2行

CSV1 - Line 2

CSV2 - 第2行

CSV2 - Line 2

CSV3 - 第2行

CSV3 - Line 2

CSV1 - 第3行

CSV1 - Line 3

CSV2 - 第3行

CSV2 - Line 3

CSV3 - 第3行

CSV3 - Line 3

....继续循环,直到CSV文件中没有行。

.... And continue to loop until there are no lines left in the CSV files.

推荐答案

尝试这个PHP代码(获取 file())。:

Try this php code (gets the lines with file()).:

<?php
$csv1 = file('csv1.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csv2 = file('csv2.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csv3 = file('csv3.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = max(count($csv1), count($csv2), count($csv3));
$finalcsv = array();
for($i=0; $i<$lines; $i++) {
  if(isset($csv1[$i])) $finalcsv[] = $csv1[$i];
  if(isset($csv2[$i])) $finalcsv[] = $csv2[$i];
  if(isset($csv3[$i])) $finalcsv[] = $csv3[$i];
}

file_put_contents('final_data.csv', implode(PHP_EOL, $finalcsv));

这篇关于如何在PHP中逐行合并CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆