Home > Article > Backend Development > How to Merge and Deduplicate Arrays of Objects Based on Unique Email Values?
Merging and Deduplicating Arrays of Objects with Unique Email Values
In the realm of data manipulation, the task of merging arrays while eliminating duplicate values can be encountered. When working with arrays of objects, it becomes essential to handle such scenarios effectively.
Consider a need to merge two arrays of objects, where each object contains an email property. The goal is to create a new array that contains all unique email values.
Sample Arrays:
$array1 = [ (object) ["email" => "gffggfg"], (object) ["email" => "[email protected]"], (object) ["email" => "wefewf"], ]; $array2 = [ (object) ["email" => "[email protected]"], (object) ["email" => "wefwef"], (object) ["email" => "wefewf"], ];
Expected Result:
[ (object) ['email' => 'gffggfg'], (object) ['email' => '[email protected]'], (object) ['email' => 'wefewf'], (object) ['email' => '[email protected]'], (object) ['email' => 'wefwef'], ]
Solution:
To merge the arrays and remove duplicates, PHP offers two useful functions:
By combining these functions, we can achieve the desired result:
$array = array_unique (array_merge ($array1, $array2));
This code snippet merges the two input arrays using array_merge() and then eliminates any duplicate email values using array_unique(). The resulting array, stored in $array, contains the distinct email values from both arrays.
The above is the detailed content of How to Merge and Deduplicate Arrays of Objects Based on Unique Email Values?. For more information, please follow other related articles on the PHP Chinese website!