我需要将具有 3 个级别的数组缩减为和的关联数组。
$consumption = [
'MONDAY' => [
'REFRIGERATOR' => [3, 9, 7],
'WASHINGMACHINE' => [2, 4, 2, 8]
],
'TUESDAY' => [
'REFRIGERATOR' => [5, 3, 8],
'OVEN' => [4, 1, 4]
],
'WEDNESDAY' => [
'TV' => [6, 9],
'REFRIGERATOR' => [2, 3, 5, 2]
],
'THURSDAY' => [
'TV' => [5, 3, 3, 2],
'FAN' => [4, 9, 8, 5]
],
'FRIDAY' => [
'WASHINGMACHINE' => [8, 5],
'OVEN' => [3, 9, 7]
]
];
我需要得到输出:
$sum = Array (
[REFRIGERATOR] => 47,
[WASHINGMACHINE] => 29,
[OVEN] => 28,
[TV] => 28,
[FAN] => 26
);
您希望将每个值存储在一个键上,并增加数组中的总数。迭代每个条目,然后从那里开始:
$sums = array();
foreach ($consumption as $day=>$products) {
foreach ($products as $product=>$sales) {
if (!isset($sums[$product])) {
$sums[$product] = 0;
}
$sums[$product] += array_sum($sales);
}
}
查看结果这里
<?php
$consumption = array( 'MONDAY' => array('REFRIGERATOR' => array(3, 9, 7), 'WASHINGMACHINE' => array(2, 4, 2, 8)), 'TUESDAY' => array('REFRIGERATOR' => array(5, 3, 8), 'OVEN' => array(4, 1, 4)), 'WEDNESDAY' => array('TV' => array(6, 9), 'REFRIGERATOR' => array(2, 3, 5, 2)), 'THURSDAY' => array('TV' => array(5, 3, 3, 2), 'FAN' => array(4, 9, 8, 5)), 'FRIDAY' => array('WASHINGMACHINE' => array(8, 5), 'OVEN' => array(3, 9, 7)) );
$result = [];
foreach($consumption as $dayCon)
{
array_walk($dayCon, function($value, $key) use(&$result)
{
if(!isset($result[$key]))
$result[$key] = 0;
$result[$key] += array_sum($value);
});
}
echo json_encode($result);
函数迭代只会为此任务添加不受欢迎的卷积。只需使用嵌套的
foreach()
循环,并根据唯一的设置键,将当前值总和添加到存储的金额或零。
代码:(演示)
$result = [];
foreach ($array as $set) {
foreach ($set as $k => $values) {
$result[$k] = ($result[$k] ?? 0) + array_sum($values);
}
}
var_export($result);