Giles Giles - 25 days ago 9
PHP Question

PHP array merge values from one array into another

Sorry I have read so many posts to make sense of this and have finally confused myself!

I have 2 arrays:

Array 1:

Array (

[0] => Array ( [ID] => SI012348 [Date] => 06/01/2016 [Month] => 1 [Tier1] => 2.188875 [Tier2] => [Tier3] => [Tier4] => [Delivery] => 0 )

[1] => Array ( [ID] => SI012351 [Date] => 06/01/2016 [Month] => 1 [Tier1] => 2.139 [Tier2] => 0 [Tier3] => 0 [Tier4] => 0 [Delivery] => 0 )

[2] => Array ( [ID] => SI012387 [Date] => 14/01/2016 [Month] => 1 [Tier1] => 0.201 [Tier2] => 0 [Tier3] => 0 [Tier4] => 0 [Delivery] => 0 )

)


Array 2: (Contains all invoices with Delivery charges)

Array (
[SI000005] => 25
[SI000010] => 15
[SI000054] => 20
[SI000069] => 0
[SI000074] => 20
[SI000076] => 16
)


I need to update Array 1 where SI00000x matches and push the value from Array 2 into the [Delivery] value in Array 1.

I am sure this is straightforward but everything I try either takes an age or crashes!

Please help!

Answer

You could use this (note the ampersand):

foreach ($arr1 as &$rec) {
    if (isset($arr2[$rec['ID']])) $rec['Delivery'] = $arr2[$rec['ID']];
}
Comments