Home  >  Article  >  Backend Development  >  How to Merge and Deduplicate Arrays of Objects Based on Unique Email Values?

How to Merge and Deduplicate Arrays of Objects Based on Unique Email Values?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 19:53:02271browse

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:

  • array_merge(): Merges the elements of multiple arrays into a single array.
  • array_unique(): Removes duplicate values from an array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn