Home  >  Article  >  Backend Development  >  取一个数组的前1000条数值,该如何解决

取一个数组的前1000条数值,该如何解决

WBOY
WBOYOriginal
2016-06-13 13:37:531980browse

取一个数组的前1000条数值

$fn = '/var/log/haproxy.log.2';
$fp = fopen($fn, 'r') or die("file open $fn false");
while($s = fgets($fp)) {
  preg_match('/\[[\d.:]+\].+\[([\d.:]+)\]/', $s, $r);
  if(empty($r[1])) continue;
  @$res[$r[1]]++;
}



fclose($fp);
asort($res);
 
print_r($res);
?>

------解决方案--------------------
你的需求这样是解决不了的

要分开处理。。。。。

比如,可将ip按第一位,写到255个文件里面,,,也可以将ip转换成数字,这样处理后续可以少用点内存

分别在255个文件里面,找出前1000名。。。因为每组至多包含2^24个不同的数【暂时不考虑ipv6】,这个内存可接受的
这样用一个数组遍历,复杂度O(n),即可找出前1000

最后维护一个1000的有序数组,往里面插入数据即可,超过1000,弹出最小的那个

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