Bibin James Bibin James - 3 months ago 25
PHP Question

merge two multidimensional array based on same ID

I am facing one issue when merging two multidimensional arrays based on the same ID.

In the example below I created two arrays -

Array1
and
Array2
. Both arrays contain objects that have an
ID
property. Based on the
ID
property, the arrays should be merged and get the result array:

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


How can I achieve this?

Answer

if these are simple objects without methods go:

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

looks messy but does the job without introducing another loop to go through object properties.