简体   繁体   中英

PHP Unique Values from Column in Array

I have an array that is generated from a SQL query that I run. 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

$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. 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:

$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. 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. Below is a code example for this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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