合并两个基于相同ID的多维数组

时间:2016-08-18 10:24:15

标签: php multidimensional-array

在基于相同ID合并两个多维数组时,我遇到了一个问题。

在下面的示例中,我创建了两个数组 - Array1Array2。两个数组都包含具有ID属性的对象。基于ID属性,应该合并数组并获取结果数组:

数组1

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] => 
    )
)

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

如果这些是没有方法的简单对象,请执行:

foreach($firstArray as $key => $firstObject){
foreach($secondArray as $secondObject){
    if($firstObject['id'] === $secondObject['id']){
        $firstArray[$key] = (object) array_merge((array) $firstObject, (array) $secondObject);
    }               
  }
}

看起来很乱,但是在不引入另一个循环来完成对象属性的情况下完成工作。