简体   繁体   中英

How to sum values of same key in array associative

I'm not getting this right when trying to sum values of keys that are same within an associative array. I thought it's gonna be easy task, but it ain't the case so please...

I'm expecting following result:

 1 -->(7) 
2 -->(14)

Here's the array:

 $array = array( 1=>4, 2=>8, 1=>3, 2=>6, );

Here's what i tried since:

$sum= array();

foreach ($array as $key => $value){ $sum[$key] += $value;} print_r($sum);

Anyway, there's no loop performed at all, since it's returning this result,

Array ( [1] => 3 [2] => 6 );

and an error,

 Undefined offset: 1 

I thought maybe there's a PHP function to handle it, but I'll be glad for any help.

What you want is impossible. Arrays cannot have duplicate keys:

php > $arr = array(1=>2, 1=>500);
php > var_dump($arr);
array(1) {
  [1]=>
  int(500)  // hey! where'd "2" go?
}

If you want to store multiple values in a single key, then that key has to point to an array:

$arr = array();
$arr[1] = array(1, 500);
var_dump($arr);
php > var_dump($arr);
array(1) {
  [1]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    int(500)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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