Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-10 19:53:02
Original
302 people have browsed it

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"],
];
Copy after login

Expected Result:

[
   (object) ['email' => 'gffggfg'],
   (object) ['email' => '[email protected]'],
   (object) ['email' => 'wefewf'],
   (object) ['email' => '[email protected]'],
   (object) ['email' => 'wefwef'],
]
Copy after login

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));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template