<?php
$keys = array(1,1,2,1,1);
$values = array(1,1,1,1,1);
$result = array_combine ($keys, $values);
?>
我想添加第二个数组值。
例如$result
将输出显示为
$result[1] = 4, // it will add the all values for the $keys of 1 ,
$result[2] = 1,
答案 0 :(得分:1)
您可以使用普通的foreach
循环。对于给定的数组$keys
和$values
,将产生$result
:
$result = [];
foreach($keys as $i => $key) {
$result[$key] = (isset($result[$key]) ? $result[$key] : 0) + $values[$i];
}
答案 1 :(得分:1)
根据您期望实现的目标,这是一种可能的解决方案:
$keys = array(1,1,2,1,1);
$values = array(1,1,1,1,1);
$total = [];
foreach($keys as $index => $key){
if(!array_key_exists($key, $total)){
$total[$key] = 0;
}
$total[$key] += $values[$index];
}
print_r($total);
答案 2 :(得分:0)
您可以这样做
$keys = array(1,1,2,1,1);
$values = array(1,1,1,1,1);
$ids = $result = [];
foreach($keys as $index => $key) {
if (in_array($key, $ids)) {
$result[$key] += $values[$index];
} else {
$result[$key] = $values[$index];
}
$ids[] = $key;
}
echo"<pre>";
print_r($result);