0
<?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,
4

3 回答 3

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);
于 2019-02-11T11:42:05.937 回答
1

你可以使用一个普通的foreach循环。对于给定的数组$keys$values这将产生$result

$result = [];
foreach($keys as $i => $key) {
    $result[$key] = (isset($result[$key]) ? $result[$key] : 0) + $values[$i];
}
于 2019-02-11T11:36:38.620 回答
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);
于 2019-02-11T11:40:16.907 回答