Quick help, I can't seem to think right now, and I need to add these array values into a single total value for each array key. Importantly the total value.

Array
(
    [0] => Array
        (
            [sub_total] => 1000
            [total_tax] => 82.5
            [total] => 1087.5
        )

    [1] => Array
        (
            [sub_total] => 120
            [total_tax] => 9.9
            [total] => 129.9
        )

)

Recommended Answers

All 5 Replies

Member Avatar for diafol

Something wrong with your maths on the first array.

A quickie:

$r = [
[
'sub_total' => 1000,
'total_tax' => 87.5,
'total' => 1087.5
],
[
'sub_total' => 120,
'total_tax' => 9.9,
'total' => 129.9
]
];

$keys = array_keys($r[0]);
$output = array_flip($keys);

foreach($r as $row)
{
    foreach($row as $key=>$value)
    {
        $output[$key] += $value;
    }
}

print_r($output);

I'm sure there's a multiarray sum function in the manual somewhere.

Thanks for the reply. The math is correct, I added an extra value to the first array before the file output.

Your solution seem to partially work, I had to suppress errors to get my desired output.

@$output = array_flip(@$total);

        foreach( $total as $row ){
          foreach( $row as $key=>$value ){
            @$output[$key] += @$value;
          }
        }

        Array
(
    [sub_total] => 1120
    [total_tax] => 92.4
    [total] => 1217.4
)

If I didn't suppress errors I would get undefined index for all indexes: 'Undefined index: sub_total, Undefined index: total_tax, Undefined index: total'.

I think will work for now, until something else breaks..

An alternative:

$t = call_user_func_array('array_merge_recursive', $r);

where $r is diafol's example array and it will return:

Array
(
    [sub_total] => Array
        (
            [0] => 1000
            [1] => 120
        )

    [total_tax] => Array
        (
            [0] => 82.5
            [1] => 9.9
        )

    [total] => Array
        (
            [0] => 1087.5
            [1] => 129.9
        )

)

Then do:

$totals = array_map("array_sum", $t);

Will return:

Array
(
    [sub_total] => 1120
    [total_tax] => 92.4
    [total] => 1217.4
)
commented: Aha - the old array functions ploy, eh? heh heh +15
Member Avatar for diafol

Your solution seem to partially work

You didn't show all the code you used e.g. array_keys(), so impossible to see why this is the case.

I really like cereal's solution - I have a soft spot for array functions - they can be notoriously slow, but they do make code far more succinct and readable.

//EDIT following a test - the loop is about x2 as fast for the code given.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.