user6606700 user6606700 - 4 months ago 16
PHP Question

Filter unique array values from three fields

How to filter the unique array values of


  • Primary Contact Email

  • Preferred Telephone

  • First Name



I'm using

array_unique($data, SORT_REGULAR);


but its checking all the values. How can I filter three fields? Sample data:

Array
(
[0] => Array
(
[First Name] => xyz
[Last Name] => abc
[Primary Contact Email] => xyz@hotmail.com
[Preferred Telephone] => 1-123-000-123
)
[1] => Array
(
[First Name] => xyz
[Last Name] => abc
[Primary Contact Email] => xyz@hotmail.com
[Preferred Telephone] => 1-123-000-123
)
[2] => Array
(
[First Name] => dss
[Last Name] => sddfs
[Primary Contact Email] => dss@hotmail.com
[Preferred Telephone] => 1-553-000-123
)
[3] => Array
(
[First Name] => dss
[Last Name] => sds
[Primary Contact Email] => dss@hotmail.com
[Preferred Telephone] => 1-444-000-123
)
[4] => Array
(
[First Name] => dss
[Last Name] => sds
[Primary Contact Email] => dss@hotmail.com
[Preferred Telephone] => 1-553-000-123
)
)


target data:

Array
(
[0] => Array
(
[First Name] => xyz
[Last Name] => abc
[Primary Contact Email] => xyz@hotmail.com
[Preferred Telephone] => 1-123-000-123
)
[2] => Array
(
[First Name] => dss
[Last Name] => sddfs
[Primary Contact Email] => dss@hotmail.com
[Preferred Telephone] => 1-553-000-123
)
[3] => Array
(
[First Name] => dss
[Last Name] => sds
[Primary Contact Email] => dss@hotmail.com
[Preferred Telephone] => 1-444-000-123
)
)

Answer

Here is my solution. The input array is called $inputs. To get it to work with your code, you'll need to change the array keys. Here I use first, mail, and phone to be brief. Your keys are First Name, Primary Contact Email, and Preferred Telephone

foreach($inputs as $input){
    $isDuplicate = false;
    foreach($results as $result){
        if(
            strtolower($input['first'])===strtolower($result['first']) &&
            strtolower($input['mail'])===strtolower($result['mail']) &&
            $input['phone']===$result['phone']
        ){
            //a duplicate was found in results
            $isDuplicate = true;
            break;
        }
    }
    //if no duplicate was found, add this input to results.
    if(!$isDuplicate) $results[]=$input;
}

Live demo

Comments