从数组中删除重复项

2022-08-30 16:49:56

我使用下面的代码行来遍历数据库中的表:

$items_thread = $connection -> fetch_all($sql);

如果我打印出阵列:

print_r($items_thread);

我会得到这个:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [1] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => lau@xx.co.uk
        )

)

但是我想摆脱数组中的重复项,所以我使用array_unique

print_r(array_unique($items_thread));

我得到下面的奇怪结果,这不是我正在寻找的:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

)

理想情况下,我认为它应该返回这个:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [1] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => lau@xx.co.uk
        )

)

我该怎么做才能把它做好?我是否使用了错误的 PHP 语法/默认函数?


答案 1

array_unique函数将为您执行此操作。您只需要添加标志:SORT_REGULAR

$items_thread = array_unique($items_thread, SORT_REGULAR);

但是,正如bren所建议的那样,如果可能的话,您应该在SQL中执行此操作。


答案 2

最好过滤掉SQL查询中的重复项。添加一个获取唯一收件人 ID 的约束