需求:找到访问小图最多的前三个ip,
日志文件20121030.log
0 192.168.1.102 small_0.gif
1 192.168.1.113 big_1.gif
2 192.168.1.110 small_2.gif
3 192.168.1.114 small_3.gif
4 192.168.1.118 small_4.gif
5 192.168.1.109 big_5.gif
6 192.168.1.110 small_6.gif
7 192.168.1.102 small_7.gif
8 192.168.1.110 small_8.gif
9 192.168.1.119 big_9.gif
10 192.168.1.112 small_10.gif
。。。中间省略。。。
91 192.168.1.112 small_91.gif
92 192.168.1.112 small_92.gif
93 192.168.1.108 small_93.gif
94 192.168.1.105 big_94.gif
95 192.168.1.117 big_95.gif
96 192.168.1.119 big_96.gif
97 192.168.1.105 big_97.gif
98 192.168.1.120 small_98.gif
99 192.168.1.114 small_99.gif
function topIp($logfile,$length=3){
$handle = fopen($logfile, 'r');
$countip = array();//统计ip
if ($handle) {
while ($buffer = fgets($handle)) {//逐行读取文件
$arr = preg_split('/\t/',$buffer);
if(strstr($arr[2],"small")){//小图
//ip为键,出现次数为指
$countip[$arr[1]] = $countip[$arr[1]] ? ++$countip[$arr[1]] : 1;
}
}
fclose($handle);
arsort($countip);//ip出现次数倒序
return array_slice($countip,0,$length);//提取
}
}
$topips = topIp('20121030.log',3);
var_dump($topips);
结果:
array(3) { ["192.168.1.110"]=> int(10) ["192.168.1.108"]=> int(8) ["192.168.1.120"]=> int(7) }