doutang3077 2016-01-24 19:40
浏览 141
已采纳

在多维数组中查找重复值

I'm trying to code a system which will find user accounts that are using the same IPs, and print out the matches with their keys. I have already coded the part where the data is pulled from MySQL and nicely put in a multidimensional associative array, so input looks like this (the key is UserID, values are IP addresses):

$users = array(
               100 => array("1.1.1.1","2.2.2.2","3.3.3.3"),
               200 => array("1.1.1.1","4.4.4.4","5.5.5.5"),
               300 => array("1.1.1.1","4.4.4.4","7.7.7.7")
              );

The expected output would be:

Array
(
    [1.1.1.1] => Array
        (
            [0] => 100
            [1] => 200
            [2] => 300
        )

    [4.4.4.4] => Array
        (
            [0] => 200
            [1] => 300
        )
)

I have searched and used trial and error with multiple nested foreach that would loop through the arrays, tried array_intersect to find the duplicates, but nothing gets me close to the expected output. By now I think I'm overthinking the problem and the solution is really easy, but I cannot seem to get close to the expected output. Any help is appreciated, thank you.

  • 写回答

2条回答 默认 最新

  • dongxie2756 2016-01-24 20:44
    关注
    $output = array();
    // loop through each user
    foreach ($users as $id => $ips) {
        // loop through each IP address
        foreach ($ips as $ip) {
            // add IP address, if not present
            if (!isset($output[$ip])) {
                $output[$ip] = array();         
            }
            // add user ID to the IP address' array
            $output[$ip][] = $id;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用sql语句实现下面两个实验(需要代码和运行结果截图)
  • ¥20 用web解决,要给我一个完整的网页,符合上述的要求
  • ¥20 求个sql代码和结果的图 两道题
  • ¥15 银河麒麟操作系统无法使用U盘
  • ¥100 寻找:光电二极管电路设计服务
  • ¥15 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁
  • ¥15 bywave配置文件写入失败