如何在 PHP 中合并对象数组并删除重复项?

DDD
发布: 2024-11-13 11:57:02
原创
678 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板