第一个数组有两个属性:
id,text
第二个数组有两个属性 id,count
如何通过id将这些组合成一个数组,其中新数组将具有三个属性:
ID 文本 计数
第一个阵列:
array(2) {
[0]=>
object(stdClass)#351 (2) {
["id"]=>
string(1) "1"
["text"]=>
string(5) "tree"
}
[1]=>
object(stdClass)#348 (2) {
["id"]=>
string(1) "2"
["text"]=>
string(8) "house"
}
第二个数组:
array(2) {
[0]=>
object(stdClass)#351 (2) {
["id"]=>
string(1) "1"
["count"]=>
string(5) "3"
}
[1]=>
object(stdClass)#348 (2) {
["id"]=>
string(1) "2"
["count"]=>
string(8) "4"
}
我试过了:
array_merge_recursive,array_merge,其中这些只将两个数组合并为一个长数组。
上述数组的预期输出:
array(2) {
[0]=>
object(stdClass)#351 (2) {
["id"]=>
string(1) "1"
["count"]=>
string(5) "3"
string(1) "1"
["text"]=>
string(5) "tree"
}
[1]=>
object(stdClass)#348 (2) {
["id"]=>
string(1) "2"
["count"]=>
string(8) "4"
string(1) "2"
["text"]=>
string(8) "house"
}
答案 0 :(得分:0)
你可以编写一个简单的函数,如果它匹配第一个数组中对象的id,它将合并第二个数组中对象的属性:
function obj_array_merge( $a1, $a2 ) {
$newAry = [];
foreach( $a1 as $idx => $obj1 ) {
// Clone object to prevent alterations to object in $a1
$newAry[$idx] = clone $obj1;
foreach($a2 as $obj2) {
/**
** If id property of both objects match,
** copy properties from second array object
** to new object (clone of first array object).
*/
if( $newAry[$idx]->id === $obj2->id ) {
foreach($obj2 as $prop => $val) {
$newAry[$idx]->$prop = $val;
}
}
}
}
return $newAry;
}
// To run:
$mergedArray = obj_array_merge( $array1, $array2 );
然而,请注意,这不会很快。由于必须迭代两个数组以检查匹配,因此对于大量对象,它可能会变得非常慢。它还将使用第二个数组对象的属性覆盖新数组对象中存在的属性(您没有指定是否存在问题)。