php处理俩个文本的效率问题

WBOY
Release: 2016-06-20 12:47:46
Original
957 people have browsed it

<?php/*==> 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);                }        }}?>
Copy after login

如代码所示,将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);  }}
Copy after login
Copy after login

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

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

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



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。

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!