PHP Group&在数组中添加元素

时间:2015-02-07 18:44:25

标签: php arrays

我有这个数组:

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
)
)

1 个答案:

答案 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));