首頁  >  文章  >  後端開發  >  如何在 PHP 中合併物件數組並刪除重複項?

如何在 PHP 中合併物件數組並刪除重複項?

DDD
DDD原創
2024-11-13 11:57:02678瀏覽

How to Merge Object Arrays and Remove Duplicates in PHP?

Merging Object Arrays and Eliminating Duplicate Values

When working with arrays of objects, it may become necessary to merge multiple arrays into a single one while ensuring the elimination of duplicate values. To achieve this, we can leverage the capabilities of PHP's built-in array functions.

Merging the Arrays

The array_merge() function comes in handy when combining two or more arrays. It appends the elements of the second array to the first, creating a new array with all the elements from both. In this case, we can use it to merge the two input arrays, $array1 and $array2, into a single array.

Removing Duplicates

To remove duplicate values, we can utilize the array_unique() function. It returns a new array with only the unique values from the input array. Duplicates are identified and excluded from the result.

Combining the Functions

By combining these two functions, we can achieve our desired goal. We first merge the two input arrays using array_merge() and then apply array_unique() to eliminate duplicate values. Here's how it looks:

$array = array_unique(array_merge($array1, $array2));

This code snippet will create a new array, $array, containing the unique objects from both $array1 and $array2. The duplicate emails will be removed.

Example Usage

Consider the following example:

$array1 = [
    (object) ["email" => "gffggfg"],
    (object) ["email" => "example@email.com"],
    (object) ["email" => "wefewf"],
];
$array2 = [
    (object) ["email" => "example@email.com"],
    (object) ["email" => "wefwef"],
    (object) ["email" => "wefewf"],
];

$array = array_unique(array_merge($array1, $array2));

print_r($array);

This code will produce the following output:

Array
(
    [0] => stdClass Object
        (
            [email] => gffggfg
        )
    [1] => stdClass Object
        (
            [email] => example@email.com
        )
    [2] => stdClass Object
        (
            [email] => wefewf
        )
    [3] => stdClass Object
        (
            [email] => wefwef
        )
)

As you can see, the duplicate email value, "example@email.com", has been removed from the merged array.

以上是如何在 PHP 中合併物件數組並刪除重複項?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn