mirvatJ
mirvatJ

Reputation: 376

how to calculate sum of total key in same array

i need to calculate the total key within the following array that contains 4 different sub arrays

Array
(
    [0] => Array
        (
            [total] => 4.2
            [sku] => 4321
        )

    [1] => Array
        (
            [total] => 2
            [sku] => 2456
        )

    [2] => Array
        (
            [total] => 3
            [sku] => 2245
        )

    [3] => Array
        (
            [total] => 1.5
            [sku] => 2674
        )

)

i was calculating it using mysql directly but i prefer to use php

$sql = "SELECT SUM(CAST(IFNULL(total,0) AS DECIMAL(10,2))) FROM trans WHERE trans.userid = :userid";

so total has to be in the same format as from the query

10.70

Upvotes: 0

Views: 242

Answers (4)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

You can also try with array_walk_recursive() like this https://eval.in/875555

$input = [your_2d_array_goes_here];
$final = array();    
array_walk_recursive($input, function($item, $key) use (&$final){
    $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});

print '<pre>';
print_r($final);
print '</pre>';
print $final['total'];
?>

Upvotes: 0

Alister Bulman
Alister Bulman

Reputation: 35149

You can loop over the array, adding up as you go, and then formatting with number_format(), or use array_column() to extract the 'total', and use array_sum() to add them, and again, using number_format() or sprintf() to format them.

echo number_format(array_sum(array_column($array, 'total')), 2);

Upvotes: 4

gautamaggarwal
gautamaggarwal

Reputation: 349

I guess something like this:-

  $array = Array
    (
        [0] => Array
            (
                [total] => 4.2
                [sku] => 4321
            )

        [1] => Array
            (
                [total] => 2
                [sku] => 2456
            )

        [2] => Array
            (
                [total] => 3
                [sku] => 2245
            )

        [3] => Array
            (
                [total] => 1.5
                [sku] => 2674
            )

    );
   $total = 0;

   foreach ($array as $key => $value) {
        $total += $value['total'];
   }

   print_r($total);

Upvotes: 1

episch
episch

Reputation: 484

you can iterate your array and sum all values like:

<?php 
$array = array(
    array(
    'total' => 4.2,
    'sku' => 4321
    ),
    array(
    'total' => 2,
    'sku' => 2456
    ),
    array(
    'total' => 3,
    'sku' => 2245
    ),
    array(
    'total' => 1.5,
    'sku' => 2674
    ),
);


$result = array('total' => 0,'sku' => 0);
foreach($array as $key => $value) {
    $result['total'] += $value['total'];
    $result['sku'] += $value['sku'];
}
var_dump($result);

Result: array(2) { ["total"]=> float(10.7) ["sku"]=> int(11696) }

for single total sum output:

echo $result['total'];

Upvotes: 0

Related Questions