Home  >  Article  >  Backend Development  >  []php处理俩个文本的效率有关问题

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

WBOY
WBOYOriginal
2016-06-13 12:25:21853browse

[求助]php处理俩个文本的效率问题

<?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,求大师指点。
------解决思路----------------------
$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 />}

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn