【问题标题】:Merge arrays together based on different values根据不同的值将数组合并在一起
【发布时间】:2011-05-24 22:53:26
【问题描述】:

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

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

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,因此数量已添加到一个键中。

有什么想法吗?

【问题讨论】:

  • 为什么不在数据库中?
  • @Ignacio Vazquez-Abrams:OP 可能无法访问 SQL 数据库,或者使用可能是一次性的并且不保证这样的开销。在代码中做完全合理的事情。虽然显然如果数据来自数据库,带有SUM()GROUP BY 子句会更可取。
  • 这不在数据库中,因为它首先从电子表格中加载,然后在加载之前对数据进行处理。

标签: php arrays merge


【解决方案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);

【讨论】:

【解决方案2】:

我会尝试类似:

   $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 是第一个 ;-)

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多