Merging Arrays with Identical Objects and Eliminating Duplicates
Merging multiple arrays into a single array is a common task in programming. However, when working with arrays containing objects, it's essential to handle duplicates carefully to avoid data integrity issues.
Consider a scenario where you have two arrays, $array1 and $array2, containing objects with an "email" property as the unique identifier. Your goal is to merge these arrays, ensuring that duplicate email values are removed.
Solution
To achieve the desired result, you can employ two PHP functions: array_merge() and array_unique().
By combining these functions, you can efficiently merge the two arrays while eliminating duplicate emails. The code below illustrates this approach:
<?php $array1 = [ (object) ["email" => "gffggfg"], (object) ["email" => "[email protected]"], (object) ["email" => "wefewf"], ]; $array2 = [ (object) ["email" => "[email protected]"], (object) ["email" => "wefwef"], (object) ["email" => "wefewf"], ]; // Merge the arrays $mergedArray = array_merge($array1, $array2); // Remove duplicate values $uniqueArray = array_unique($mergedArray, SORT_REGULAR); // Print the merged and unique array print_r($uniqueArray); ?>
Output:
Array ( [0] => stdClass Object ( [email] => gffggfg ) [1] => stdClass Object ( [email] => [email protected] ) [2] => stdClass Object ( [email] => wefewf ) [3] => stdClass Object ( [email] => wefwef ) )
As you can see, the resulting $uniqueArray contains only unique email values, successfully merging and deduplicating the two input arrays.
The above is the detailed content of How can I merge arrays with identical objects and eliminate duplicates in PHP?. For more information, please follow other related articles on the PHP Chinese website!