0

What is the best way to remove any duplicate rows from my output based on the e-mail address field?

I have tried using array_unique however it removed far too many e-mails.

Output Array:

$guestOutput[] = [

                    'firstName' => $guest->guestFirstName,
                    'lastName' => $guest->guestLastName,
                    'email' => $guest->guestEmail,
                ];

Array Example:

  [0]=>
  array(3) {
    ["firstName"]=>
    string(5) "T"
    ["lastName"]=>
    string(6) "B"
    ["email"]=>
    string(21) "glh@gmail.com"
  }
  [1]=>
  array(3) {
    ["firstName"]=>
    string(5) "L"
    ["lastName"]=>
    string(7) "Kr"
    ["email"]=>
    string(23) "email1@gmail.com"
  }

My end goal is that I am creating a CSV file :)

Jess McKenzie
  • 8,345
  • 27
  • 100
  • 170

4 Answers4

1

A simple way if you are using a loop to add the details in ( which is what I am assuming your current code is doing) is to index the $guestOutput by the e-mail address. So as you add in new details, you will just overwrite the previous details...

$guestOutput[$guest->guestEmail] = [
                    'firstName' => $guest->guestFirstName,
                    'lastName' => $guest->guestLastName,
                    'email' => $guest->guestEmail,
                ];

If you don't need the index at the end of the loop, you can use:

$guestOutput = array_values($guestOutput);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

It's best to build the array with email as the key to avoid duplicates in the first place, but if you can't, then re-index with email and eliminate the duplicates:

$guestOutput = array_column($guestOutput, null, 'email');

Re-index to integer keys if needed:

$guestOutput = array_values(array_column($guestOutput, null, 'email'));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

As mentioned the prefered option would be to change how the data is stored before assiging it to guesOutput. If you dont have control over this you could use the following.

$aSortedArray = array();
foreach($gustOutput as $iPos => &$a){   
    if(!isset($aSortedArray[$a['email']])){
        $aSortedArray[$a['email']] =& $a;
    }else{
        // handle duplicate
    }
}
atoms
  • 2,993
  • 2
  • 22
  • 43
0

You can use array_intersect_key,array_unique,array_column

$res = array_intersect_key($arr, array_unique(array_column($arr, 'email')));

Live Demo

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20