Home >Backend Development >PHP Tutorial >How can I merge arrays with identical objects and eliminate duplicates in PHP?

How can I merge arrays with identical objects and eliminate duplicates in PHP?

DDD
DDDOriginal
2024-11-15 07:05:041059browse

How can I merge arrays with identical objects and eliminate duplicates in PHP?

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().

  1. array_merge(): This function merges elements from multiple arrays into a single array.
  2. **array_unique(): This function removes duplicate values from an array, ensuring that each value occurs only once.

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!

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