当前位置:Gxlcms > PHP教程 > []php处理俩个文本的效率有关问题

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

时间:2021-07-01 10:21:17 帮助过:21人阅读

[求助]php处理俩个文本的效率问题
  1. <!--?php<br /-->/*<br><br>==> 1.txt <==<br>a:123<br>b:1333<br>c:333<br><br>==> 2.txt <==<br>a:3333<br>aa:3433<br>c:323dfa<br><br>==> result.txt <==<br>a:123:3333<br>c:333:323dfa<br><br>*/<br><br><br>$file_1 = "1.txt";<br>$file_2 = "2.txt";<br><br>$f = fopen("$file_1", 'r') or die("Cann't Open the file.");<br><br>while (!(feof($f))) {<br> $line = explode(':', trim(fgets($f)));<br> $f2 = fopen("$file_2", 'r') or die("Cann't Open the file.");<br> while (!(feof($f2))) {<br> $line2 = explode(':', trim(fgets($f2)));<br> if ($line[0] == $line2[0]) {<br> $line[] = $line2[1];<br> $aaaa = implode(":",$line);<br> $output_file = fopen("./result.txt", 'a');<br> echo "$aaaa\n";<br> fwrite($output_file, "$aaaa\n");<br> fclose($output_file);<br> }<br><br> }<br>}<br>?>

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

没有嵌套的循环,不会太慢的

人气教程排行