我有一个大海捞针,我想分别对每个数组的值求和。这就是我所拥有的:
Array //ALL THE HAYSTACK
(
[0] => Array //REPRESENTS MONTH 1
(
[0] => Array //REPRESENTS WEEK 1
(
[week] => 1
[user1] => Array
(
[0] => Array
(
[sell] => value
[cost] => value
[gain] => value
)
)
[user2] => Array
(
[0] => Array
(
[sell] => value
[cost] => value
[gain] => value
)
)
[user3] => Array
(
[0] => Array
(
[sell] => value
[cost] => value
[gain] => value
)
)
)
//... MORE WEEKS
[1] => Array //REPRESENTS MONTH 2
( //... ALL THE PROCCES ABOVE
)
我正在尝试每个月和每周使用foreach()
,如下所示:
$result = $array('sell' => 0, 'cost' => 0, 'gain' => 0);
foreach ($monthArray as $theMonth => $week){
foreach ($week as $user){
$result['sell'] += $user['user1'][0]['sell'];
$result['sell'] += $user['user2'][0]['sell'];
$result['sell'] += $user['user3'][0]['sell'];
//...
但是,当我每个月打印$result
时,不是我想要的特定月份......
我想每周和每个月都要求和。怎么解决这个问题?
答案 0 :(得分:0)
这个怎么样?:结果($sales
)是一个数组。这个数组的键是月份,数组的值是总数。通过迭代本月的几周,然后每周迭代用户来获得总数。我自己介绍的后一次迭代,因为您使用的是user1,user2,user3 ....这个硬编码列表....
不是将它存储在另一个数组中,您也可以立即回声或使用它,但我认为在数组中使用它更方便进一步处理。它稍微解开了你的代码。
$result = $array('sell' => 0, 'cost' => 0, 'gain' => 0);
foreach ($monthArray as $theMonth => $week){
$sales[$theMonth] = 0;
foreach ($week as $users){
foreach ($users as $user) {
$sales[$theMonth] += $user[0]['sell'];
}
}
}
result['sell'] = $sales;
print_r(result['sell']);
如果您希望每个月也有成本和收益,那么创建一个格式为$result[month]['sell']
而不是$result['sell'][month]
更有意义。
答案 1 :(得分:0)
您可以尝试使用array_reduce()和array_column()。一个例子:这里:
//$array = your array
$sum_arr = array_reduce($array, function($old, $new){
$arr = array_filter(array_map(function($v){ return is_array($v) ? $v : '';}, array_shift($new)));
return [
'sell' => array_sum(array_column($arr, 'sell')) + $old['sell'],
'cost' => array_sum(array_column($arr, 'cost')) + $old['cost'],
'gain' => array_sum(array_column($arr, 'gain')) + $old['gain'],
];
}, ['sell'=>0, 'cost'=>0, 'gain'=>0]);
<强>更新强>
array_column()
的替代方案:
$sum_arr = array_reduce($array, function($old, $new){
$arr = array_filter(array_map(function($v){ return is_array($v) ? $v : '';}, array_shift($new)));
return [
'sell' => array_sum(array_map(function($v){return $v['sell'];}, $arr)) + $old['sell'],
'cost' => array_sum(array_map(function($v){return $v['cost'];}, $arr)) + $old['cost'],
'gain' => array_sum(array_map(function($v){return $v['gain'];}, $arr)) + $old['gain'],
];
}, ['sell'=>0, 'cost'=>0, 'gain'=>0]);