如何获得多维数组的总和

时间:2016-12-01 04:00:35

标签: php arrays sum

有阵列

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

需要输出:

$sum= Array ( [REFRIGERATOR] => 47, [WASHINGMACHINE] => 29 ,[OVEN] => 28, [TV] => 28, [FAN] => 26 );

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:3)

检查结果Apple PushKit

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