根据不同的值将数组合并在一起

时间:2011-05-24 22:53:27

标签: php arrays merge

我无法通过以下问题思考逻辑:

我有以下数组(已被剪断,因为它更大)

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,因此将qty添加到一个键中。

有什么想法吗?

2 个答案:

答案 0 :(得分: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 :(得分: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是第一个; - )