2016-08-18 72 views
0

当基于相同ID合并两个多维数组时,我面临一个问题。合并两个基于相同ID的多维数组

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

数组1

Array 
(
[0] => stdClass Object 
    (
     [claimtotal] => 
     [total] => 4 
     [ID] => 3 

    ) 

[1] => stdClass Object 
    (
     [claimtotal] => 20 
     [total] => 1 
     [ID] => 4 
    ) 
) 

数组2

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

请告诉我们你为了得到想要的结果而试过的东西 – Epodax

回答

1

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

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

看起来杂乱无章,但做这项工作没有引入另一个循环都要经过对象的属性。