2011-05-24 33 views
2

我有以下的問題的邏輯的麻煩思想:合併陣列一起根據不同的數值

我有以下陣列(已被剪斷,作爲其更大)

Array 
(
    [0] => Array 
     (
      [code] => LAD001 
      [whqc] => GEN 
      [stocktag] => NONE 
      [qty] => 54 
     ) 

    [1] => Array 
     (
      [code] => LAD001 
      [whqc] => GEN 
      [stocktag] => NONE 
      [qty] => 6 
     ) 

    [2] => Array 
     (
      [code] => LAD004 
      [whqc] => HOLD 
      [stocktag] => NONE 
      [qty] => 6 
     ) 

) 

我基本上需要在這個數組中使用所有的鍵,這樣在代碼whqc和stocktag相同的情況下,將qty值加在一起。用下面的例子中,我需要與此落得:

Array 
(
    [0] => Array 
     (
      [code] => LAD001 
      [whqc] => GEN 
      [stocktag] => NONE 
      [qty] => 60 
     ) 

    [1] => Array 
     (
      [code] => LAD004 
      [whqc] => HOLD 
      [stocktag] => NONE 
      [qty] => 6 
     ) 

) 

作爲陣列的第一和第二密鑰具有相同的代碼,whqc和stocktag,該數量的已被添加一起放入一個密鑰。

任何想法?

+0

爲什麼不在這個數據庫中的? – 2011-05-24 22:54:40

+2

@Ignacio Vazquez-Abrams:OP可能無法訪問SQL數據庫,或者使用情況可能是一次,並且不保證這種開銷。在代碼中完成合理的事情。儘管顯然如果數據來自數據庫,那麼帶有「SUM()」的GROUP BY子句將更可取。 – Orbling 2011-05-24 23:06:42

+0

這不是在數據庫中,因爲它首先從電子表格中加載,然後在加載數據之前對其進行處理。 – Lock 2011-05-24 23:18:24

回答

1

我建議將組值設置爲散列,將整個數組存儲在散列下面作爲關鍵字,如果您有重複項,請添加數量,然後執行array_values()以提取結果。

$aggregated = array(); 
foreach ($records as $cRec) { 
    // The separator | has been used, if that appears in the tags, change it 
    $cKey = md5($cRec['code'] . '|' . $cRec['whqc'] . '|' . $cRec['stocktag']); 

    if (array_key_exists($cKey, $aggregated)) { 
     $aggregated[$cKey]['qty'] += $cRec['qty']; 
    } else { 
     $aggregated[$cKey] = $cRec; 
    } 
} 

// Reset the keys to numerics 
$aggregated = array_values($aggregated); 
+1

那完全是我以後做的。非常感謝! – Lock 2011-05-24 23:17:56

+0

@Lock:歡迎!以備日後參考:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235 – 2011-05-24 23:21:34

1

我會嘗試這樣的:

$output = array(); 
    foreach($array as $details){ 
     //make distinct key 
     $key = $details['code'].'_'.$details['whqc']; 
     if(!isset($output[$key])){ 
      $output[$key] = $details; 
     }else{ 
      $output[$key]['qty'] += $details['qty']; 
      $output[$key]['stocktag'] = $details['stocktag']; 
     } 
    } 
    $output = array_values($output); 
    print_r($output); 

更新:Orbling是第一;-)

相關問題