找到相同的两个键数组时如何分组和计算值数组

时间:2012-03-06 05:18:20

标签: php arrays grouping

我有这样的php数组:

Array ( 
[0] => Array ([electronics] => TV [condition] => GOOD [1] => 100 [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 
[1] => Array ([electronics] => TV [condition] => NOTGOOD [1] => 50 [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 
[2] => Array ([electronics] => AC [condition] => GOOD [1] => 200 [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 
[3] => Array ([electronics] => TV [condition] => GOOD [1] => 50 [2] => 30 [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 
[4] => Array ([electronics] => AC [condition] => GOOD [1] => 50 [2] => 30 [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 
)

然后我想通过[电子]和[条件]进行分组和计算。 (在该数组中找到相同的[电子]和[条件]时计算)。 结果我想这样:

Array ( 
[0] => Array ([electronics] => TV [condition] => GOOD [1] => 150 [2] => 30 [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 
[1] => Array ([electronics] => TV [condition] => NOTGOOD [1] => 50 [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 
[2] => Array ([electronics] => AC [condition] => GOOD [1] => 250 [2] => 30 [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => ) 
)

1 个答案:

答案 0 :(得分:0)

这应该是一种方法:

$result = array();
foreach ($arrays as $array) {
    $key = $array['electronics'] . $array['condition'];
    foreach ($array as $k => $v) {
        if (is_numeric($k)) {
            $result[$key][$k] += $v;
        } else {
            $result[$key][$k] = $v;
        }
    }
}

$result = array_values($result);