简体   繁体   English

使用第一个数组作为键组合两个数组(但有重复项),然后添加具有匹配重复项的第二个数组值

[英]Combining two arrays using the first array as key(but has duplicates) then adding the second array values that has the matching duplicates

I want to combine two arrays. 我想结合两个数组。 First use the first array as the key(combining the duplicates) then add the values from the second array to adjust to the specific keys 首先使用第一个数组作为键(合并重复项),然后将第二个数组中的值相加以适应特定的键

//first array  
array('1','0','1'); 
//second array 
array('50','10','20');

//output -> first array ('1','0') second array -> ('70','10')

removing the duplicates in the first array and adding the corresponding "duplicate" key in the second array values 删除第一个数组中的重复项,并在第二个数组值中添加相应的“ duplicate”键

Use a result array to collect the outcomes like this: 使用结果数组来收集如下结果:

//first array  
$k = array('1','0','1'); 
//second array 
$v = array('50','10','20');

$result = array();

foreach($k as $index => $value) {
    if(!isset($result[$value])) {
        $result[$value] = 0;
    }
    $result[$value] += $v[$index];
}

print_r($result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM