gpt4 book ai didi

php - 如何在 PHP 中合并两个对象数组

转载 作者:IT王子 更新时间:2023-10-29 00:11:35 26 4
gpt4 key购买 nike

我有以下两个对象数组:

第一个数组: $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 排序。

期望的输出:

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 个简单的步骤完成了工作:

//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 的回答帮助我找到了这个简单的解决方案

关于php - 如何在 PHP 中合并两个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11877586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com