2014-07-24 114 views
0

我一直在試圖讓代碼以某種格式輸出數據,所以我可以在圖表中使用它,並希望在最後階段獲得一些幫助。提前致謝。總和月度數組值

這是我的代碼,產生下面的數組。

$monthly_sales_array = array(); 
    $i=0; 
    foreach($ord as $sales) 
    { 
     $month_is = date('m-Y',$sales->order_date); 
     $monthly_sales_array['months'][$month_is][$i] = $sales->qty*$sales->price_per; 
     $i++; 
    } 

Array 
(
[months] => Array 
    (
     [07-2014] => Array 
      (
       [0] => 33 
       [1] => 33 
       [2] => 26 
       [3] => 26 
       [4] => 38.5 
       [5] => 33 
       [6] => 165     
      ) 

     [06-2014] => Array 
      (
       [21] => 0.01 
       [22] => 44 
       [23] => 48 
      ) 
    ) 
) 

試圖讓這個結局:

Array(
[months] => Array 
    (
     [07-2014] => 354.5 
     [06-2014] => 92.01 
    ) 
) 

回答

0

嘗試這樣:

$monthly_sales_array = array(); 
$my_array = array(
    'months' => array(
     '07-2014' => array(
       '0' => '33', 
       '1' => '33', 
       '2' => '26', 
       '3' => '26', 
       '4' => '38.5', 
       '5' => '33', 
       '6' => '165' ,     
      ), 

     '06-2014' => array(
       '21' => '0.01', 
       '22' => '44', 
       '23' => '48', 
      ) 
     ) 
); 


foreach ($my_array['months'] as $key => $value) { 
    $sum = array_sum(array_map(function ($a) { return $a; }, $my_array['months'][$key])); 
    $monthly_sales_array['months'][$key] = $sum;  
} 
print_r($monthly_sales_array); 

OUTPUT:

Array 
(
    [months] => Array 
     (
      [07-2014] => 354.5 
      [06-2014] => 92.01 
     ) 

) 
0

你需要一個foreach。 (還有其他的方法可以做到這一點,但我覺得這是最簡單的)

foreach($monthly_sales_array['months'] as &$month) { 
    $total=0; 
    foreach($month as $day) { 
    $total+=$day; 
    } 
    $month=$total; 
} 

注:&運營商foreach($monthly_sales_array['months'] as &$month)意味着,當你更新$month,它會在$monthly_sales_array更新。