Skip to content Skip to sidebar Skip to footer

Distinguish Duplicates In A Foreach Loop From Sql

Hi so Im creating a job application management system. in the backend the admin needs to be able to see all those who have applied for a job and awaiting a response. here is my sql

Solution 1:

Alternative - let the database do the work for you:

SELECT j.*, c.appl_count FROM jp_applications j
    INNER JOIN (SELECT user_id, count(1) as appl_count FROM jp_applications
            WHERE application_status = "Awaiting Response"
            GROUP BY user_id) c on c.user_id = j.user_id
WHERE j.application_status = "Awaiting Response"
ORDER BY j.job_id

Then your resultset will have the field 'appl_count' available, if greater than 1, append the class. This removes the need to do any tit-for-tat accounting in the app code.


Solution 2:

On each loop iteration, check if the user_id key exists in your "already_matched" array. If it doesn't, append your class. Otherwise, do nothing

semi php-ish pseudo code:

$already_matched = array(); 
foreach($results as $result) { 
    if(!array_key_exists($result['user_id'],$already_matched)) { 
         $already_matched[$result['user_id']] = true;
        // append the css class. This is the first match
     }
     else { 
        // This is the second and all subsequent matches
     } 
}

Solution 3:

You can efficiently detect duplicates using a php array:

$applicants = array();
// $results = query results

foreach($results as $application) {
    $is_duplicate = !empty($applicants[$applicants['user_id']]);

    echo '<span class="' . ($is_duplicate ? 'duplicate' : '') . '">Application here</span>'=

    $applicants[$application['user_id']] = $application;
}

I left out all the database handling code, since it seems like you have that already under control. The point is to create an entry in an array indexed by the user id, then check that on each iteration to see if you've already looped over that user.


Post a Comment for "Distinguish Duplicates In A Foreach Loop From Sql"