0

I have this array:

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
)

How can I get below array with php? I need to group "types" adding "amount" & "amount", but omitting elements without type value

Array(
[0] => Array(
[type] => 15.0
[base] => 24.0
[amount] => 3.6
)
[1] => Array(
[type] => 2.0
[base] => 12.0
[amount] => 0.24
)
)
1
  • Are you really grouping or are you just tying to omit them? For example what happens if you have more than one array with the same type value but different amount values? Commented Feb 7, 2015 at 18:52

1 Answer 1

1

array_reduce comes to the rescue:

$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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.