Tracking duplicate deletion within a cartesian product

    // Remove duplicate database entries
    $delete=$db->prepare('deleteModule','modules');
    foreach($data->output['modules'] as $dbModule){
        foreach($data->output['modules'] as &$dbModule2){
            if(
                $dbModule['name'] == $dbModule2['name'] 
                &&
                $dbModule['id'] != $dbModule2['id']
            ){
                $delete->execute(array(':id' => $dbModule2['id']));
                unset($dbModule2);
            }
        }
    }

The issue here is that if you have a duplicate (or more than one, but assume one for explanation purposes) and you unset the current $dbModule2 item from the array (as seen here) it doesn’t actually mark it properly. This is because it’s not being unset from the top level loop array ($dbModule) so it still later comes to down to evaluate the item that has been unset from the lower level loop array ($dbModule2) and identifies the original item as a duplicate. Therefor, instead of only deleting the latest duplicate(s) it actually deletes all records that have a duplicate without leaving the original intact.

The solutions may vary, but if the if the current item within the lower level loop array ($dbModule2) that is first identified as a duplicate was also unset from the top level loop array ($dbModule) then this issue would be resolved, right? How can this (or a better solution?) be implemented?

I solved this problem but in the spirit of sharing and appreciation for the community I am posting the solution here for discussion, those that end up here in future searches, etc.

    // Remove duplicate database entries
    $delete=$db->prepare('deleteModule','admin_modules');
    foreach($data->output['modules'] as $dbModule){
        foreach($data->output['modules'] as $key => $dbModule2){
            if(isset($duplicatedModules))
                if(in_array($dbModule2['id'],$duplicatedModules))
                    continue;
            if($dbModule['name']==$dbModule2['name'] 
            && $dbModule['id']!=$dbModule2['id']) {
                $delete->execute(array(':id' => $dbModule2['id']));
                unset($data->output['modules'][$key]);
                $duplicatedModules[]=$dbModule['id'];
            }
        }
    }