<?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,
<?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,
根据您期望实现的目标,这是一个可能的解决方案:
$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);
你可以使用一个普通的foreach
循环。对于给定的数组$keys
,$values
这将产生$result
:
$result = [];
foreach($keys as $i => $key) {
$result[$key] = (isset($result[$key]) ? $result[$key] : 0) + $values[$i];
}
你可以这样做
$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);