php處理倆個文本的效率問題

來源:互聯網
上載者:User
 1.txt <==a:123b:1333c:333==> 2.txt <==a:3333aa:3433c:323dfa==> result.txt <==a:123:3333c: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);  }}

沒有嵌套的迴圈,不會太慢的

$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);  }}

沒有嵌套的迴圈,不會太慢的



1.txt 2.89M, 2.txt 3.12M
運行之後提示:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)
php.ini裡設定的是memory_limit = 128M,一下就用光了嗎?

會有這種事?檔案並不大嘛。
可能是其他的原因

你把這兩個檔案放到雲端硬碟上

直接設定 memory_limit = 1024M,速度快多了,非常感謝@xuzuning。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.