2015-02-07 20 views
0

元素我有此数组:PHP集团及新增数组

Array(
[0] => Array(
[type] => 
[base] => 10.0 
[amount] => 0 
) 
[1] => Array(
[type] => 15.0 
[base] => 12.0 
[amount] => 1.8 
) 
[2] => Array(
[type] => 15.0 
[base] => 12.0 
[amount] => 1.8 
) 
[3] => Array(
[type] => 2.0 
[base] => 12.0 
[amount] => 0.24 
) 

我怎样才能获得以下数组用PHP?我需要一群“类型”,并称“量” &“量”,但省略不类型值的元素

Array(
[0] => Array(
[type] => 15.0 
[base] => 24.0 
[amount] => 3.6 
) 
[1] => Array(
[type] => 2.0 
[base] => 12.0 
[amount] => 0.24 
) 
) 
+0

你真的分组还是你只是搭售省略它们?例如,如果您有多个具有相同“类型”值但数量不同的值的数组会发生什么情况? – prodigitalson 2015-02-07 18:52:23

回答

1

array_reduce就派上用场了:

$result = array_reduce($array, function($memo, $item) { 
    if (!isset($item['type'])) return $memo; 
    if (!isset($memo['' . $item['type']])) { // first occurence 
     $memo['' . $item['type']] = $item; 
    } else {         // will sum 
     $memo['' . $item['type']]['base'] += $item['base']; 
     $memo['' . $item['type']]['amount'] += $item['amount']; 
    } 
    return $memo; 
}, array()); 

var_dump(array_values($result));