如何合并在PHP对象的两个数组 [英] How to merge two arrays of object in PHP
本文介绍了如何合并在PHP对象的两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有对象的以下两个数组:
第一个数组: $数组1
阵列
(
[0] => stdClass的对象
(
[ID] => 100
[名] =>穆罕默德
) [1] => stdClass的对象
(
[ID] => 102
[名] =>易卜拉欣
) [2] => stdClass的对象
(
[ID] => 101
[名] => Sumayyah
)
)
第二个数组: $数组2
阵列
(
[0] => stdClass的对象
(
[ID] => 100
[名] =>穆罕默德
) [1] => stdClass的对象
(
[ID] => 103
[名] =>优素福
)
)
我要合并这两个对象的数组(删除所有副本),并根据号的顺序排列
。
所需的输出:
阵列
(
[0] => stdClass的对象
(
[ID] => 100
[名] =>穆罕默德
) [1] => stdClass的对象
(
[ID] => 101
[名] => Sumayyah
) [2] => stdClass的对象
(
[ID] => 102
[名] =>易卜拉欣
) [3] => stdClass的对象
(
[ID] => 103
[名] =>优素福
)
)
解决方案
这3个简单的步骤做的工作:
//两个数组将被合并包括重复
$结果= array_merge($数组1,$数组2);
//重复的对象将被删除
$结果= array_map(反序列化,array_unique(array_map(连载,$结果)));
//数组进行排序上的id的基
排序($结果);
注意:按@Kamran回答让我来到这个简单的解决方案。
I have the following two arrays of objects:
First Array: $array1
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => Muhammad
)
[1] => stdClass Object
(
[id] => 102
[name] => Ibrahim
)
[2] => stdClass Object
(
[id] => 101
[name] => Sumayyah
)
)
Second Array: $array2
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => Muhammad
)
[1] => stdClass Object
(
[id] => 103
[name] => Yusuf
)
)
I want to merge these two object arrays (removing all duplicates) and sorted according to id
.
Desired output:
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
)
)
解决方案
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 );
Note: Answer by @Kamran helped me come to this simple solution
这篇关于如何合并在PHP对象的两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文