添加来自两个不同数组php的值


Adding values from two diffrent arrays php

我的代码执行过程中得到了两个数组,如下所示:

$one = array("IN","US","IN","JP");
$two = array("10","20","30","40");

在上述情况下,每个值的顺序是相同的。即IN = 10.的第一个值对于US = 20
我想添加相同国家的值。因此,对于印度来说,我总共有40个
我不知道该怎么解决这个问题。

您可以合并两个数组,并使用第一个数组中的值作为索引。

$one = array("IN","US","IN","JP");
$two = array("10","20","30","40");
$merge = array();
// Loop through the first array
foreach($one as $index => $value){
    // If the country has not been set before, create the index
    if(!isset($merge[$value]))
        $merge[$value] = $two[$index];
    else // Add the value if it's not the first time we 'see' this country
        $merge[$value] += $two[$index];
}

现在,如果你做$merge['IN'],它会给你40

var_dump:的结果

array(3) { 
    ["IN"]=> int(40) 
    ["US"]=> string(2) "20"
    ["JP"]=> string(2) "40" 
}