我在合并基于相同ID的两个多维数组时面临一个问题。
在下面的例子中,我创建了两个数组——Array1
和Array2
。这两个数组都包含具有ID
属性的对象。根据ID
属性,对数组进行合并,得到结果数组:
Array1
Array
(
[0] => stdClass Object
(
[claimtotal] =>
[total] => 4
[ID] => 3
)
[1] => stdClass Object
(
[claimtotal] => 20
[total] => 1
[ID] => 4
)
)
Array2
Array
(
[0] => stdClass Object
(
[ID] =>2
[name] => test1
)
[1] => stdClass Object
(
[ID] => 3
[name] => test2
)
[2] => stdClass Object
(
[ID] =>4
[name] => test3
)
[3] => stdClass Object
(
[ID] => 5
[name] => test4
)
)
Result_array
Array
(
[0] => stdClass Object
(
[ID] =>2
[name] => test1
[claimtotal] =>
[total] =>
)
[1] => stdClass Object
(
[ID] => 3
[name] => test2
[claimtotal] =>
[total] => 4
)
[2] => stdClass Object
(
[ID] =>4
[name] => test3
[claimtotal] => 20
[total] => 1
)
[3] => stdClass Object
(
[ID] => 5
[name] => test4
[claimtotal] =>
[total] =>
)
)
我怎样才能做到这一点?
如果这些是没有方法的简单对象,则执行
foreach($firstArray as $key => $firstObject){
foreach($secondArray as $secondObject){
if($firstObject['id'] === $secondObject['id']){
$firstArray[$key] = (object) array_merge((array) $firstObject, (array) $secondObject);
}
}
}
看起来很乱,但是没有引入另一个循环来遍历对象属性。