我有一个数组,我需要通过添加值来处理,然后删除任何添加的重复项。
这是原始阵列......
Array (
[0] => Array ( [PID] => 2872 [QTY] => 1 )
[1] => Array ( [PID] => 3145 [QTY] => 2 )
[2] => Array ( [PID] => 3107 [QTY] => 1 )
[3] => Array ( [PID] => 2739 [QTY] => 1 )
[4] => Array ( [PID] => 3137 [QTY] => 1 )
[5] => Array ( [PID] => 3107 [QTY] => 1 )
[6] => Array ( [PID] => 2739 [QTY] => 1 )
[7] => Array ( [PID] => 3107 [QTY] => 1 )
[8] => Array ( [PID] => 3137 [QTY] => 4 )
[9] => Array ( [PID] => 3551 [QTY] => 1 )
[10] => Array ( [PID] => 3107 [QTY] => 1 )
[11] => Array ( [PID] => 3107 [QTY] => 1 )
[12] => Array ( [PID] => 3137 [QTY] => 1 )
[13] => Array ( [PID] => 3551 [QTY] => 2 )
[14] => Array ( [PID] => 3136 [QTY] => 1 )
[15] => Array ( [PID] => 3137 [QTY] => 1 )
[16] => Array ( [PID] => 3032 [QTY] => 1 )
[17] => Array ( [PID] => 3551 [QTY] => 1 )
[18] => Array ( [PID] => 3107 [QTY] => 1 )
[19] => Array ( [PID] => 3459 [QTY] => 1 )
[20] => Array ( [PID] => 3141 [QTY] => 1 )
[21] => Array ( [PID] => 2724 [QTY] => 1 )
[22] => Array ( [PID] => 2743 [QTY] => 1 )
[23] => Array ( [PID] => 3139 [QTY] => 2 )
[24] => Array ( [PID] => 3137 [QTY] => 2 )
[25] => Array ( [PID] => 3107 [QTY] => 1 )
)
我需要做的是获取此数组并从相同的[PID]值添加[QTY]值,然后在此结束后使用这样的数组......
Array (
[0] => Array ( [PID] => 2724 [QTY] => 1 )
[1] => Array ( [PID] => 2739 [QTY] => 2 )
[2] => Array ( [PID] => 2743 [QTY] => 1 )
[3] => Array ( [PID] => 2872 [QTY] => 1 )
[4] => Array ( [PID] => 3032 [QTY] => 1 )
[5] => Array ( [PID] => 3107 [QTY] => 7 )
[6] => Array ( [PID] => 3136 [QTY] => 1 )
[7] => Array ( [PID] => 3137 [QTY] => 9 )
[8] => Array ( [PID] => 3139 [QTY] => 2 )
[9] => Array ( [PID] => 3141 [QTY] => 1 )
[10] => Array ( [PID] => 3145 [QTY] => 2 )
[11] => Array ( [PID] => 3459 [QTY] => 1 )
[12] => Array ( [PID] => 3551 [QTY] => 4 )
)
所以添加所有QTY然后删除重复项。
我不太确定在这里继续前进的最佳方式。有什么建议吗?
答案 0 :(得分:2)
循环遍历它们,创建一个新的数组,其中PID为键,QTY为值,因此您可以添加后者。
foreach ($array as $row) {
list($pid, $qty) = $row;
$sums[$pid] += $qty;
}
显然你可以抛出一个isset
来压制通知。
如果您需要以前的阵列结构,请再次转换它。
答案 1 :(得分:1)
我只是使用一个简单的循环:
$combined = array();
// $org will be the original structure
foreach($org as $id => $data) {
$pid = $data['PID'];
if(!isset($combined[$pid])) {
$combined[$pid] = $data;
} else {
$combined[$pid]['QTY'] += $data['QTY'];
}
}
// return keys to normal indexs instead of the PID
array_values($combined);