首页 > 解决方案 > PHP 在每一行的末尾附加一行来自另一个文本

问题描述

我有两个文本文件。第一个包含:

1,
1,
1,
1,

第二个包含:

3,4,5,
6,7,8,
0,8,9,
12,4,6,

我想得到的输出是:

1,3,4,5,
1,6,7,8,
1,0,8,9,
1,12,4,6,

基本上是用 PHP 在第一个文本文件的每一行末尾附加第二个文本文件中的一行。

$handle = fopen("data/data1.txt", "r");

      //what needs to be appended
      $fileContents = file_get_contents('output.txt');
      $fixedFileContents = preg_replace('/.+/', '$0$handle', $fileContents);
      file_put_contents($fixedFileContents, 'output.txt.txt');

代码完全错误......提前谢谢你!

标签: php

解决方案


为此使用file()

$first_page_array = file("data/data1.txt",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$second_page_array = file("provide second file path",FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$final_array = [];

foreach($first_page_array as $key=>$first_page){
   $final_array[] = $first_page.','.$second_page_array[$key];
}
print_r( $final_array);

file_put_contents('output.txt.txt',$final_array);

推荐阅读