从sql中区分foreach循环中的重复项

时间:2013-10-15 15:57:09

标签: php mysql sql

您好我正在创建一个工作申请管理系统。在后端,管理员需要能够看到所有申请工作并等待回复的人。这是我的SQL查询:

'SELECT * FROM jp_applications WHERE application_status = "Awaiting Response" ORDER BY job_id'

我的问题是,一旦我循环并在申请人列表中输出这个,我希望能够在该列表元素中添加一个类(如果它是重复的申请人)。 (一个人申请一份以上的工作)。

理想情况下,我希望列表由job_id排序,所以我不想通过说user_id来订购它。

我希望这是有道理的。

<ul>
    <li class="duplicate">Joe Bloggs</li>
    <li>Michael Jackson</li>
    <li>Gandalf the Grey</li>
    <li>Mahatma Gandhi</li>
    <li class="duplicate">Joe Bloggs</li>
    <li>Daffy Duck</li>
    <li>Sponegbob Squarepants</li>
    <li>Will Smill</li>
</ul>

3 个答案:

答案 0 :(得分:3)

替代方案 - 让数据库为您完成工作:

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

然后你的结果集将有'appl_count'字段可用,如果大于1,则追加该类。这样就无需在应用程序代码中进行任何针锋相对的会计处理。

答案 1 :(得分:0)

在每次循环迭代中,检查user_id键是否存在于“already_matched”数组中。 如果没有,请附上你的课程。否则,什么都不做

半php-ish伪代码:

$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
     } 
}

答案 2 :(得分:0)

您可以使用php数组有效地检测重复项:

$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;
}

我遗漏了所有数据库处理代码,因为看起来你已经掌控了它。关键是要在用户标识索引的数组中创建一个条目,然后在每次迭代时检查一下,看看你是否已经遍历该用户。

相关问题