2015-10-20 76 views
0

我有一個存儲值的多維數組,並且我想添加數組中每個元素的值並返回總值的數組。如何在多維數組中添加值

我已經創建了以下可以工作的函數,但它的目的似乎很臃腫。有沒有更簡單和更乾淨的方式來做到以下幾點?

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

您可以構建關鍵value1,使一個for循環從1到8這會節省一些代碼:

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; 
} 
0

,我可以看到你正在試圖返回列的總和你的功能可以像這樣優化。

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