我有这个数组:
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 :(得分: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));