按第二级键对 3d 数组中的数据进行分组,并对每组的第三级值求和

问题描述 投票:0回答:3

我需要将具有 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
);
php arrays multidimensional-array sum grouping
3个回答
4
投票

您希望将每个值存储在一个键上,并增加数组中的总数。迭代每个条目,然后从那里开始:

$sums = array();
foreach ($consumption as $day=>$products) {
    foreach ($products as $product=>$sales) {
        if (!isset($sums[$product])) {
            $sums[$product] = 0;
        }
        $sums[$product] += array_sum($sales);
    }
}

3
投票

查看结果这里

<?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);

0
投票

函数迭代只会为此任务添加不受欢迎的卷积。只需使用嵌套的

foreach()
循环,并根据唯一的设置键,将当前值总和添加到存储的金额或零。

代码:(演示

$result = [];
foreach ($array as $set) {
    foreach ($set as $k => $values) {
        $result[$k] = ($result[$k] ?? 0) + array_sum($values);
    }
}
var_export($result);
© www.soinside.com 2019 - 2024. All rights reserved.