如何在 PHP 中合并两个对象数组 [英] How to merge two arrays of object in PHP

查看:161
本文介绍了如何在 PHP 中合并两个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个对象数组:

I have the following two arrays of objects:

第一个数组: $array1

Array
(
    [0] => stdClass Object
        (
            [id] => 100
            [name] => Muhammad
        )

    [1] => stdClass Object
        (
            [id] => 102
            [name] => Ibrahim
        )

    [2] => stdClass Object
        (
            [id] => 101
            [name] => Sumayyah
        )
)

第二个数组: $array2

Array
(
    [0] => stdClass Object
        (
            [id] => 100
            [name] => Muhammad
        )

    [1] => stdClass Object
        (
            [id] => 103
            [name] => Yusuf
        )
)

我想合并这两个对象数组(去除所有重复项)并根据id排序.

I want to merge these two object arrays (removing all duplicates) and sorted according to id.

期望的输出:

Array
(
    [0] => stdClass Object
        (
            [id] => 100
            [name] => Muhammad
        )

    [1] => stdClass Object
        (
            [id] => 101
            [name] => Sumayyah
        )

    [2] => stdClass Object
        (
            [id] => 102
            [name] => Ibrahim
        )

    [3] => stdClass Object
        (
            [id] => 103
            [name] => Yusuf
        )
)

推荐答案

这 3 个简单的步骤完成了工作:

These 3 simple steps did the work:

//both arrays will be merged including duplicates
$result = array_merge( $array1, $array2 );
//duplicate objects will be removed
$result = array_map("unserialize", array_unique(array_map("serialize", $result)));
//array is sorted on the bases of id
sort( $result );

注意:@Kamran 的回答帮助我找到了这个简单的解决方案

Note: Answer by @Kamran helped me come to this simple solution

这篇关于如何在 PHP 中合并两个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆