i have an array like 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 i have to find the total sales of each color in the array.
The result array should be like
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 as $value) {
foreach ($value as $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
)
Here's a sample algorithm:
foreach
on main array,foreach
on second level array,array_sum
and add it to existing valueYou can do like this
$tsales = array();
foreach ($sales as $key => $value) {
foreach ($value as $key => $val) {
$tsales[$key] += array_sum($val);
}
}
echo '<pre>';
print_r($tsales);
echo '</pre>';
Try this:
$val = array();
foreach($sales as $values){
foreach($values as $k => $v){
$val[$k] = (array_key_exists($k, $val)) ? $val[$k] + array_sum($v) : array_sum($v);
}
}
Output:
Array
(
[RED] => 46
[GREEN] => 19
[YELLOW] => 11
[BLUE] => 20
[BLACK] => 26
)
Here is short solution using array_walk
, key_exists
and array_sum
functions:
$total = [];
array_walk($sales, function($v) use(&$total){
foreach ($v as $k => $arr) {
$total[$k] = (key_exists($k, $total))? $total[$k] + array_sum($arr) : array_sum($arr);
}
});
print_r($total);
The output:
Array
(
[RED] => 46
[GREEN] => 19
[YELLOW] => 11
[BLUE] => 20
[BLACK] => 26
)