简体   繁体   English

数组中列的 PHP 唯一值

[英]PHP Unique Values from Column in Array

I have an array that is generated from a SQL query that I run.我有一个从我运行的 SQL 查询生成的数组。 It looks like the following:它看起来像下面这样:

$arr[$i]['id'] = $id;
$arr[$i]['name'] = $name;
$arr[$i]['email'] = $email;

How can I get the unique values from the email column?如何从电子邮件列中获取唯一值? I appreciate the help.我很感激你的帮助。

最佳答案是:

array_unique(array_column($arr, 'email'))

Either filter it in your column using the DISTINCT method in MySQL, or use something like使用 MySQL 中的 DISTINCT 方法在您的列中过滤它,或者使用类似的方法

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

Since PHP 5.5, a new function called array_column() is also available.自 PHP 5.5 起,还提供了一个名为array_column()的新函数。 You can use it following way:您可以通过以下方式使用它:

$allEmails = array_column($arr, 'email');
$uniqueEmails = array_unique($allEmails);

Remove duplicates from array comparing a specific key从比较特定键的数组中删除重复项

Consider the same array but id of 3rd index is different:考虑相同的数组,但第三个索引的 id 不同:

$all_array = Array
(
    [0] => Array
        (
            [id] => 1
            [value] => 111
        )

    [1] => Array
        (
            [id] => 2
            [value] => 222
        )

    [2] => Array
        (
            [id] => 3
            [value] => 333
        )

    [3] => Array
        (
            [id] => 4
            [value] => 111
        )
)

Now, both 1 & 4 have same values.现在,1 和 4 具有相同的值。 So we want to remove any of them:所以我们想删除它们中的任何一个:

$unique_arr = array_unique( array_column( $all_array , 'value' ) );
print_r( array_intersect_key( $all_array, $unique_arr ) );

If you get the list sorted by email from SQL you can improve performance by looping through the array like Gareth does, but instead only compare current email address with the last inserted email address.如果您从 SQL 获得按电子邮件排序的列表,您可以通过像 Gareth 那样循环遍历数组来提高性能,但只将当前电子邮件地址与最后插入的电子邮件地址进行比较。 Below is a code example for this:下面是一个代码示例:

$uniqueEmails = array();
$lastemail = '';
foreach($arr as $array)
{
    if($array['email'] != $lastemail)
    {
        $uniqueEmails[] = $array['email'];
        $lastemail = $array['email'];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM