如何按值删除重复的数组元素并保留最新的条目?

时间:2016-07-26 15:58:37

标签: php mysql arrays

这是我的查询,内部查询给了我一个按日期排序的数组,但如果我使用group by它保持随机重复而不是第一个或最后一个。在我的情况下,可能有多个约会具有相同的患者ID,但我只需要最新的。有没有办法我可以使用PHP来保持重复值的第一次出现并删除其余的同时保持日期排序或在查询中执行?

$sql = 'SELECT * 
FROM (
    SELECT a.patient_id, a.appointment_datetime, b.first_name, b.last_name, b.email 
    FROM '.TABLE_APPOINTMENTS.' a, '.TABLE_PATIENTS.' b 
    WHERE doctor_id='.$doctor_id.' AND a.patient_id = b.id 
    ORDER BY appointment_datetime desc) AS t 
GROUP BY patient_id';

输出:

Array ( [0] => Array ( [patient_id] => 1 [appointment_datetime] => 
 [1] =>  Array ( [patient_id] => 2 [appointment_datetime] => ) 
[2] => Array ( [patient_id] => 3 [appointment_datetime] => )
 [3] => Array ( [patient_id] => 5 [appointment_datetime] => 
[4] => Array ( [patient_id] => 20 [appointment_datetime] => 2016-06-29 17:30:00 ) )

内部查询的输出:

Array ( [0] => Array ( [patient_id] => 20 [appointment_datetime] => 2016-07-14 17:00:00 
) [1] =>Array ( [patient_id] => 20 [appointment_datetime] => 2016-07-05 23:00:00 ) 
[2] => Array ( [patient_id] => 20 [appointment_datetime] => 2016-06-29 17:30:00 ) 
[3] => Array ( [patient_id] => 20 [appointment_datetime] => 
 [4] =>Array ( [patient_id] => 20 [appointment_datetime] => )
 [5] = Array ( [patient_id] => 20 [appointment_datetime] => )
[6] => Array ( [patient_id] => 1 [appointment_datetime] => ) 
[7] => Array ( [patient_id] => 2 [appointment_datetime] => ) 
[8] => Array ( [patient_id] => 3 [appointment_datetime] => )
[9] => Array ( [patient_id] => 5 [appointment_datetime] => ) )

解决方案:

$sql = 'SELECT a.patient_id, max(a.appointment_datetime), b.first_name, b.last_name, b.email 
    FROM '.TABLE_APPOINTMENTS.' a, '.TABLE_PATIENTS.' b 
    WHERE doctor_id='.$doctor_id.' AND a.patient_id = b.id 
    GROUP BY a.patient_id ORDER BY a.appointment_datetime';

2 个答案:

答案 0 :(得分:1)

用户in_array删除重复值,然后尝试将唯一值推送到新数组。

$unique = array();
foreach($array as $arr)
{
if(!in_array($arr, $unique))
{
$unique[] = $arr;
}
}

通过这个,您将获得所有第一个值。并删除所有副本。在数组值中使用此概念。它会像魅力一样工作

答案 1 :(得分:1)

尝试直接在查询中指定您想要最新的条目:

$sql = 'SELECT * 
    FROM (
        SELECT a.patient_id, MAX(a.appointment_datetime), b.first_name, b.last_name, b.email 
            FROM '.TABLE_APPOINTMENTS.' a, '.TABLE_PATIENTS.' b 
            WHERE doctor_id='.$doctor_id.' AND a.patient_id = b.id 
            ORDER BY appointment_datetime desc) AS t 
    GROUP BY patient_id';

注意MAX()已添加到查询中。

祝你好运!