2013-08-18 82 views
0

這是我使用的數組(3層),我試圖將第一個數組中的第一個月的銷售數量(nosales)添加到第一個數組中的第一個月第二個數組(應該是150)等等,通過所有變量(月份不應該被添加),所以我留下了一個兩級數組,每個月有nosales,salevalue,salecost和saleprofit總數。總結三層數組的內容PHP

Array (
     [0] => Array 
      (
       [1] => Array 
        (
         [month] => 1 
         [nosales] => 100 
         [salevalue] => 1200 
         [salecost] => 360 
         [saleprofit] => 840 
        ) 

       [2] => Array 
        (
         [month] => 2 
         [nosales] => 110 
         [salevalue] => 1320 
         [salecost] => 396 
         [saleprofit] => 924 
        ) 

      ) 

     [1] => Array 
      (
       [1] => Array 
        (
         [month] => 1 
         [nosales] => 50 
         [salevalue] => 350 
         [salecost] => 70 
         [saleprofit] => 280 
        ) 

       [2] => Array 
        (
         [month] => 2 
         [nosales] => 55 
         [salevalue] => 385 
         [salecost] => 77 
         [saleprofit] => 308 
        ) 

      ) 

    ) 

現在,我已經嘗試循環他們,讓他們加在一起,但我收到了一些錯誤。有人可以幫忙嗎?

這裏是我用此刻的腳本:

$acc = array_shift($results_array); 

foreach ($results_array as $val) { 
    foreach ($val as $v) { 
     foreach ($v as $key => $v){ 
     $acc[$key] += $v; 
     } 
    } 
} 

感謝您的幫助提前!

+0

您想添加第一個月還是隻想添加第一個月的第一個月,第二個月是第二個月?什麼是預期產出? – invisal

+0

我希望從第一個月的值被編譯到第一個月,第二個月到第二個月,所以我留下了一個單一的數組,這是他們所有人的總數。似乎有人已經給我正確的答案了:)謝謝。 – JamesJ

回答

0

這是你想要做的嗎?

$aResultsArray = array(
    0 => array(
     1 => array(
      'month' => 1, 
      'nosales' => 100, 
      'salevalue' => 1200, 
      'saleconst' => 360, 
      'saleprofit' => 840, 
     ), 
     2 => array(
      'month' => 2, 
      'nosales' => 110, 
      'salevalue' => 1320, 
      'saleconst' => 396, 
      'saleprofit' => 924, 
     ), 
    ), 
    1 => array(
     1 => array(
      'month' => 1, 
      'nosales' => 50, 
      'salevalue' => 350, 
      'saleconst' => 70, 
      'saleprofit' => 280, 
     ), 
     2 => array(
      'month' => 2, 
      'nosales' => 55, 
      'salevalue' => 385, 
      'saleconst' => 77, 
      'saleprofit' => 308, 
     ), 
    ), 
); 

$aSum = array(); 
foreach ($aResultsArray as $mYear => $aMonths) { 
    foreach ($aMonths as $mMonth => $aMonth) { 

     if (!isset($aSum[$aMonth['month']])) { 
      $aSum[$aMonth['month']] = array(
       'month' => $aMonth['month'], 
       'nosales' => 0, 
       'salevalue' => 0, 
       'saleconst' => 0, 
       'saleprofit' => 0, 

      ); 
     } 

     $aSum[$aMonth['month']]['nosales'] += $aMonth['nosales']; 
     $aSum[$aMonth['month']]['salevalue'] += $aMonth['salevalue']; 
     $aSum[$aMonth['month']]['saleconst'] += $aMonth['saleconst']; 
     $aSum[$aMonth['month']]['saleprofit'] += $aMonth['saleprofit']; 

    } 
} 
var_dump($aSum); 
+0

謝謝,它的確如我所願。 – JamesJ