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 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误