2011-05-24 38 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是第一;-)

相关问题