当前位置: 代码迷 >> PHP >> []php处理俩个文本的效率有关问题
  详细解决方案

[]php处理俩个文本的效率有关问题

热度:97   发布时间:2016-04-28 16:57:38.0
[求助]php处理俩个文本的效率问题
<?php
/*

==> 1.txt <==
a:123
b:1333
c:333

==> 2.txt <==
a:3333
aa:3433
c:323dfa

==> result.txt <==
a:123:3333
c:333:323dfa

*/


$file_1 = "1.txt";
$file_2 = "2.txt";

$f = fopen("$file_1", 'r') or die("Cann't Open the file.");

while (!(feof($f))) {
        $line = explode(':', trim(fgets($f)));
        $f2 = fopen("$file_2", 'r') or die("Cann't Open the file.");
        while (!(feof($f2))) {
                $line2 = explode(':', trim(fgets($f2)));
                if ($line[0] == $line2[0]) {
                        $line[] = $line2[1];
                        $aaaa = implode(":",$line);
                        $output_file = fopen("./result.txt", 'a');
                        echo "$aaaa\n";
                        fwrite($output_file, "$aaaa\n");
                        fclose($output_file);
                }

        }
}
?>

如代码所示,将1.txt和2.txt整理输出到一个新文件result.txt, 效果如注释部分。我写的代码处理的条数少的时候没发现问题,当俩个文本都有十几万条记录的时候,效率就出大事了,要整理10来个小时。初学PHP,求大师指点。
------解决思路----------------------
$t = file('data/1.txt', FILE_IGNORE_NEW_LINES);
foreach($t as $v) {
  list($k, $v) = explode(':', $v);
  $a[$k][] = $v;
}
$t = file('data/2.txt', FILE_IGNORE_NEW_LINES);
foreach($t as $v) {
  list($k, $v) = explode(':', $v);
  $b[$k][] = $v;
}
foreach($a as $k=>$v) {
  if(isset($b[$k])) {
    file_put_contents('data/result.txt', join(':', array_merge(array($k), $v, $b[$k])). PHP_EOL, FILE_APPEND);
  }
}

没有嵌套的循环,不会太慢的
  相关解决方案