从数组中删除重复项 [英] Remove duplicate items from an array
本文介绍了从数组中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下面的代码行遍历我数据库中的一个表:
I use the line of code below to loop through a table in my database:
$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
But I want to get rid of the duplicate items in the array, so I use array_unique
print_r(array_unique($items_thread));
我得到了以下奇怪的结果,这并不是我想要的:
I get the weird result below which is not quite I am looking for:
Array
(
[0] => Array
(
[RecipientID] => 3
[RecipientScreenname] => Tom L
[RecipientFirstname] => Thomas
[RecipientEmail] => info@xx.com
)
)
理想情况下,我认为它应该返回:
Ideally, I think it should return this:
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 语法/默认函数?
What shall I do to get it right? Have I used the wrong PHP syntax/default function?
推荐答案
array_unique
函数会为你做这件事.您只需要添加 SORT_REGULAR
标志:
$items_thread = array_unique($items_thread, SORT_REGULAR);
但是,正如 bren 所建议的那样,您如果可能,应该在 SQL 中执行此操作.
However, as bren suggests, you should do this in SQL if possible.
这篇关于从数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文