php - How to find the sum of an associative array -


i have array this

$sales = array('first'=>array('red'=>array(9,3),'green'=>array(4,5,8,2)),  'second'=>array('red'=>array(3,5,5,2),'yellow'=>array(4,2,5)), 'third'=>array('blue'=>array(1,2,4),'red'=>array(9,4,6)),  'four'=>array('blue'=>array(2,3,3,5),'black'=>array(4,5,8,9))); 

and have find total sales of each color in array.

the result array should

array('red'=>46,'green'=>19, ...) 

use array_sum inside foreach:

$sales = array('first'=>array('red'=>array(9,3),'green'=>array(4,5,8,2)),  'second'=>array('red'=>array(3,5,5,2),'yellow'=>array(4,2,5)), 'third'=>array('blue'=>array(1,2,4),'red'=>array(9,4,6)),  'four'=>array('blue'=>array(2,3,3,5),'black'=>array(4,5,8,9)));  $arr = [];  foreach ($sales $value) {     foreach ($value $key => $val) {         if(array_key_exists($key, $arr)){             $arr[$key] += array_sum($val);         } else {             $arr[$key] = array_sum($val);         }     } }  print_r($arr); 

result:

array (     [red] => 46     [green] => 19     [yellow] => 11     [blue] => 20     [black] => 26 ) 

demo


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo