我有一个像这样的数组
$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)));
我必须找到阵列中每种颜色的总销售额。
结果数组应该像
Array('RED'=>46,'GREEN'=>19, ...)
答案 0 :(得分:5)
以下是使用array_walk
,key_exists
和array_sum
函数的简短解决方案:
$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);
输出:
Array
(
[RED] => 46
[GREEN] => 19
[YELLOW] => 11
[BLUE] => 20
[BLACK] => 26
)
答案 1 :(得分:3)
在foreach中使用array_sum:
$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);
结果:
Array
(
[RED] => 46
[GREEN] => 19
[YELLOW] => 11
[BLUE] => 20
[BLACK] => 26
)
答案 2 :(得分:1)
试试这个:
$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);
}
}
<强>输出:强>
Array
(
[RED] => 46
[GREEN] => 19
[YELLOW] => 11
[BLUE] => 20
[BLACK] => 26
)
答案 3 :(得分:0)
以下是一个示例算法:
foreach
foreach
,array_sum
并将其添加到现有值答案 4 :(得分:0)
你可以这样做
$tsales = array();
foreach ($sales as $key => $value) {
foreach ($value as $key => $val) {
$tsales[$key] += array_sum($val);
}
}
echo '<pre>';
print_r($tsales);
echo '</pre>';