dougua9328 2016-01-07 10:11
浏览 18
已采纳

如果阵列有超过10个元素......那么什么?

I have a top 10 list right here. The list contains all the IPs who visited the domain (out of my log files) and my code below gives me the top 10 IPs of them.

But I want it more dynamically. Like if there are more then 10 different IPs, give me just the 10 IPs that appear the most. If the amount of different IPs is less then 10, just give me all the IPs there are.

The code for this:

$all_ips = array_count_values($ip_array);
arsort($all_ips);
$count = count($all_ips);
$keys = array_keys($all_ips);
$topTenIp = array();
$count = $count -1;

for($i=0; $i <= $count; $i++){
    if($count < 9){
        $topTenIp[] = $keys[$i];
    }else{
        $topTenIp[] = $keys[$i];
    }
}

This works okay but not perfect. If the amount of IPs is below 10, it gives me all the IPs there are. But if there are more then 10, it doesn't give me the 10 most appearing IPs, it just gives me all IPs of the log script.

I hope you understood what I was trying to say. I'm from Germany, so my English isn't that good.

Thanks anyway :)

  • 写回答

4条回答 默认 最新

  • dongzice4895 2016-01-07 10:18
    关注

    What you're doing isn't logical. Say $all_ips is 30 then every 30 iterations will execute in the else. Resulting in a array of 30 ip's.

    You'll need to change your if and else part.

        for($i=0; $i <= $count; $i++){
            if($i < 9){
                $topTenIp[] = $keys[$i];
            } else {
                 break; //Break out of the loop
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作