问题描述
|
我在思考具有以下问题的逻辑时遇到麻烦:
我有以下数组(已被截断,因为它更大)
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,因此将数量添加到一个键中。
有任何想法吗?
解决方法
我建议将组值组合到一个散列中,将整个数组存储在散列下作为键,如果有重复项,则添加数量,然后执行“ 2”来提取结果。
$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);
,我会尝试类似的东西:
$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 ;-)