如何在多维数组中添加值

时间:2015-10-20 05:35:48

标签: php

我有一个存储值的多维数组,我想在数组中添加每个元素的值,并返回总值的数组。

我已经创建了以下可以正常工作的功能,但它的目的看起来非常臃肿。是否有更简单,更清洁的方式来执行以下操作?

function get_totals($metric_array){
    $totals['value1']=0;
    $totals['value2']=0;
    $totals['value3']=0;
    $totals['value4']=0;
    $totals['value5']=0;
    $totals['value6']=0;
    $totals['value7']=0;
    $totals['value8']=0;

    foreach ($metric_array as $metric){
        $totals['value1']=$totals['value1']+$metric['value1'];
        $totals['value2']=$totals['value2']+$metric['value2'];
        $totals['value3']=$totals['value3']+$metric['value3'];
        $totals['value4']=$totals['value4']+$metric['value4'];
        $totals['value5']=$totals['value5']+$metric['value5'];
        $totals['value6']=$totals['value6']+$metric['value6'];
        $totals['value7']=$totals['value7']+$metric['value7'];
        $totals['value8']=$totals['value8']+$metric['value8'];  
    }
    return $totals;
}

2 个答案:

答案 0 :(得分:2)

您可以构造键value1,并从1到8进行for循环。这样可以保存一些代码:

function get_totals($metric_array){
  for ($i = 1; $ <= 8; $i++) {
    $key = 'value' . $i;
    $totals[$key] = 0;
    foreach ($metric_array as $metric){
      $totals[$key] += $metric[$key];
    }
  }
  return $totals;
}

答案 1 :(得分:0)

正如我所见,您正在尝试返回列的总和。您的函数可以像这样进行优化。

    function get_totals($metric_array){
        $totals = array();
        foreach ($metric_array as $metric){
            foreach ($metric as $key => $val){
                $totals[$key] += $val;
            }  
        }
        return $totals;
    }