draj30958 2016-09-21 21:59
浏览 68
已采纳

PHP:如何在合并三个或更多文件中的每一行后将正确的输出到文件中?

I'm trying to merge all the lines from three or more files. Each line must be merged with every single line from these files. Each file could have any amount of lines.

Content of files is like this:

file1.txt:
    file1 line1
    file1 line2
file2.txt:
    file2 line1
    file2 line2
file3.txt:
    file3 line1
    file3 line2

As a PHP newbie I've wrote such a code:

<?php
$file1 = file("file1.txt");
$file2 = file("file2.txt");
$file3 = file("file3.txt");
$file777 = fopen("file777.txt", "w");
for($f1=0;$f1<count($file1);$f1++)
    for($f2=0;$f2<count($file2);$f2++)
        for($f3=0;$f3<count($file3);$f3++)
            fwrite($file777, "$file1[$f1] $file2[$f2] $file3[$f3]");
fclose($file777);
?>

But in the result file I'm getting a mess like this:

file1 line1
 file2 line1
 file3 line1
file1 line1
 file2 line1
 file3 line2file1 line1
 file2 line2 file3 line1
file1 line1
 file2 line2 file3 line2file1 line2 file2 line1
 file3 line1
file1 line2 file2 line1
 file3 line2file1 line2 file2 line2 file3 line1
file1 line2 file2 line2 file3 line2

Instead of a needed result like this:

file1 line1 file2 line1 file3 line1
file1 line1 file2 line1 file3 line2
file1 line1 file2 line2 file3 line1
file1 line1 file2 line2 file3 line2
file1 line2 file2 line1 file3 line1
file1 line2 file2 line1 file3 line2
file1 line2 file2 line2 file3 line1
file1 line2 file2 line2 file3 line2

Could you help me to get a proper output please?

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • duan1396 2016-09-21 22:05
    关注

    You're not removing the newlines at the end of each line.

    From the php.net manual for file()

    Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

    Use trim to remove the newlines.

    <?php
    $file1 = file("file1.txt");
    $file2 = file("file2.txt");
    $file3 = file("file3.txt");
    $file777 = fopen("file777.txt", "w");
    for($f1=0;$f1<count($file1);$f1++)
        for($f2=0;$f2<count($file2);$f2++)
            for($f3=0;$f3<count($file3);$f3++)
                fwrite($file777, trim($file1[$f1]) ." ". trim($file2[$f2] ) ." ".  trim($file3[$f3]) .PHP_EOL );
    fclose($file777);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退