PHP数组将值从一个数组合并到另一个数组

时间:2016-11-08 21:41:21

标签: php arrays

对不起,我已经阅读了很多帖子来理解这一点并最终让自己感到困惑!

我有2个阵列:

数组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 ) 

)

数组2 :(包含所有带运费的发票)

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

我需要更新SI00000x匹配的阵列1,并将阵列2中的值推送到阵列1中的[Delivery]值。

我确信这很简单,但我尝试的一切都需要一个年龄或崩溃!

请帮忙!

3 个答案:

答案 0 :(得分:3)

你可以使用它(注意ampersand):

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

答案 1 :(得分:1)

试试这个(使用参考)

foreach ($array1 as &$a1) {
  if(isset($array1[$a1['ID']])) $a1['Delivery'] = $array1[$a1['ID']];
}

答案 2 :(得分:0)

foreach ($array1 as &$a1) {
    if (isset($array2[$a1['ID']])) {
        $a1['Delivery'] = $array2[$a1['ID']];
    }
}