简体   繁体   中英

How to sum value of array if some values are same?

I have following array

Array (
    [0] => 1995,17500
    [1] => 2052,17500
    [2] => 2052,17500
    [3] => 2236,30000
    [4] => 2235,15000
    [5] => 2235,40000
);

I have exploded the value with comma ,.

foreach($array as $key=>$value) {

      $newar = explode(',', $value);
}

So I have similar first value ie $newar["0"]. For example 2235 and 2052. And I would like to have sum of second value ie $newar["1"].

How can I achieve following result with PHP.

Array (
   [0] => 1995, 17500
   [1] => 2052, 35000
   [2] => 2036, 30000
   [3] => 2235, 55000
)

You can create a new array key/index based and use array_key_exists to check if the key already exists. If so sum the value, if not create the key. This is not the exact result you want, but it's neater.

$newar = []; //New Array

foreach($array as $value) {
     $explArr = explode(',', $value);

     if(array_key_exists($explArr[0], $newar)){ //Check if the key already exists
        $newar[$explArr[0]] += $explArr[1]; //Sum value to existing key
     } else {
        $newar[$explArr[0]] = $explArr[1]; //Create key
     }
}

Your result array will look like this:

Array (
   [1995] => 17500
   [2052] => 35000
   [2036] => 30000
   [2235] => 55000
)

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