I have an array that contains ip addresses and their respective subnet information. In a first time, I have to add the subnets informations into my database but I'm trying to do so without any duplicate, with this code
#Note that this is pseudo-code
foreach ($subnets as $subnet)
{
$query = 'INSERT INTO subnets (field1, field2)
VALUES ($subnet['subnet'], $subnet['netmask']);'
$database->executeQuery($query);
$query = 'SELECT id FROM subnets
WHERE subnet = $subnet['subnet']
AND mask = $subnet['netmask'];'
$subnet_id = $database->getRow($query);
foreach ($subnets as $key => $subnet_check)
{
if (($subnet['subnet'] == $subnet_check['subnet']) AND ($subnet['netmask'] == $subnet_check['netmask']))
{
$ip_to_add = array_merge($ip_to_add,array(array("subnet_id" => $subnet_id[0], "ip" => $subnet['ip'], "name" => $subnet['name'])));
unset($subnets[$key]);
}
}
}
The first foreach will add every subnet and retrieve each of their id. The second foreach will scan every subnet and try to find a duplicate (including itself). If it does, it should add the ip addresse information an array and then, unset this element since we don't want to re-insert the subnet in another loop.
Yet, this does not seem to unset it correctly since in the end, every subnets and ip addresses are inserted (inserting all the subnet brings a lot of duplicates).
Could anyone explain to me why the unset is not working correctly? Is it because I'm into a 2 level foreach?
Thank you.