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.
$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;
}
}
$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")
);
$allIP = [];
foreach ( $users as $user ) {
$allIP = array_merge($allIP, $user);
}
$allIP = array_unique($allIP);
$result = [];
foreach ( $allIP as $ip ) {
foreach ( $users as $key => $val ) {
if ( in_array($ip, $val, true) ) {
if ( !isset($result[$ip]) ) {
$result[$ip] = [];
}
array_push($result[$ip], $key);
}
}
}
$result = array_filter($result, function ($v, $k) {
if ( count($v) > 1 ) {
return true;
} else {
return false;
}
}, ARRAY_FILTER_USE_BOTH);
var_dump($result);
Although I think it's better to do this by SQL as well. It could be extremely slow to achieve this by PHP.