0

I want to convert the following 3-level array to a flat, associative array of columnar sums per first level key. Do I need to use a foreach() or can array_sum() do this?

[
    'Sum_1' => [
        ['e' => 1000001, 'u' => 'Test1', 'a' => 775.00],
        ['e' => 26, 'u' => 'Test2', 'a' => 555.00],
    ],
    'Sum_2' => [
        ['e' => 1000001, 'u' => 'Test1', 'a' => 110.00],
    ],
    'Sum_3' => [
        ['e' => 1000001, 'u' => 'Test1', 'a' => 444.00],
    ],
]

I want to get the sum of element [a] of each section (e.g. Sum_1, Sum_2, Sum_3).

Desired result:

[
    'Sum_1' => 1330.00,
    'Sum_2' => 110.00,
    'Sum_3' => 444.00,
]
0

3 Answers 3

6

You could do like this:

$ret = array_map(function($val) {
  return array_sum(array_map(function($val) {
     return $val['a'];
  }, $val));
}, $array);

Prior to php 5.4:

function a_getter($val) {
    return $val['a'];
}
$ret = array_map(function($val) {
    return array_sum(array_map('a_getter', $val));
}, $array);
Sign up to request clarification or add additional context in comments.

3 Comments

@xdazz I was able to do the sums without an array, on the template itself. Thank you anyway. I don't really understand your method. I know what array_map and array_sum do, but can't really understand how they are used in your code? can you explain a bit or direct me to a useful source? Thank you
@ThiliniIW Check how array_map work will be help. array_map — Applies the callback to the elements of the given arrays
"Callables" can be used from php 5.4
0

Make mapped calls of array_sum() on the a column values of each data subset.

Code: (Demo)

var_export(
    array_map(
        fn($rows) => array_sum(
            array_column($rows, 'a')
        ),
        $array
    )
);

Or use nested loops and perform basic arithmetic on the nominated column values. Remember to default the key's value to 0 if it has not yet been pushed into the result array -- this avoids PHP Warnings.

Code: (Demo)

$result = [];
foreach ($array as $k => $rows) {
    foreach ($rows as ['a' => $a]) {
        $result[$k] = ($result[$k] ?? 0) + $a;
    }
}
var_export($result);

Comments

0

Using a foreach loop, you can try this:

$sums=array();
foreach($ArrayOfSums as $Offset=>$ArrayOfResults){
    foreach($ArrayOfResults as $ResultOffset=>$Result){
        $sums[$Offset]+=$Result["a"];
    }
}

Result:

Warning: Undefined array key "Sum_1"

Warning: Undefined array key "Sum_2"

Warning: Undefined array key "Sum_3"
array (
  'Sum_1' => 1330.0,
  'Sum_2' => 110.0,
  'Sum_3' => 444.0,
)

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.