tags:

views:

66

answers:

3

Array for example

$array = array(
  array('first'=>5), array('first'=>4), array('second'=>3)
);

How sum values by keys for result:

$result = array(
  'first'=>9,
  'second'=>3
);

Thanks in advance.

+3  A: 

you can iterate array $array and do whatever you want. And you can do it with any language if you have some pprogramming skills.

$result=array();
foreach ($array as $sub) {
  foreach ($sub as $key => $value) {
    if (isset($result[$key])) $result[$key] += $value;
    else $result[$key]=$value;
  }
}

Note: if you getting this info from database, it is better to sum it using database resources.

Col. Shrapnel
A: 

You can use array_walk_recursive:

$results = array();
array_walk_recursive($array, function($number, $key){
    global $results;
    if (! isset($results[$key])) $results[$key] = 0;
    $results[$key] += $number;
});

This works in php >= 5.3

Nicolò Martini
A: 

Col. Shrapnel, yes it's work, but result

foreach ($count_groups as $sub) {    
  foreach ($sub as $key => $value) {    
  echo $key." ";    
    if (isset($result[$key])) $result[$key] += $value;    
    else $result[$key]=$value;    
  }    
echo $result[$key]."<br>";

is list

$first - 5

$first - 9

$second - 3

but need final result

$first - 9

$second - 3

THANKS!!!

Andrew Spilak
You are printing through each loop, try `var_dump($result);` after the outer `foreach` I bet it has your results correctly. Also, this really shouldn't be an answer on your own question, its common to comment instead in replies. Please clean it up when you get a chance.
gnarf
sorry, but I does not see comment link for comment Col. Shrapnel
Andrew Spilak
thank you, all ok
Andrew Spilak