Matt Elhotiby
Matt Elhotiby

Reputation: 44066

calucating the total of the price field in an array

( [0] => Array 
( [0] => Array ( 
[0] => Array ( [price] => 76  ) 
[1] => Array ( [price] => 200  ) 
[2] => Array ( [price] => 500  ) 
[3] => Array ( [price] => 67  ) 

is there a clean way to calculate all these prices

Upvotes: 1

Views: 410

Answers (1)

Jim
Jim

Reputation: 18853

Doing some digging at the array_sum() manual (reading in the user section) I came across this function:

function array_sum_key( $arr, $index = null ){
    if(!is_array( $arr ) || sizeof( $arr ) < 1){
        return 0;
    }
    $ret = 0;
    foreach( $arr as $id => $data ){
        if( isset( $index )  ){
            $ret += (isset( $data[$index] )) ? $data[$index] : 0;
        }else{
            $ret += $data;
        }
    }
    return $ret;
}

How I would in-vision you using it, given the remarks at the manual

$sum = array_sum_key($products[0][0], 'price');

Hopefully it works out for you, as that should be an easy solution :)

Upvotes: 2

Related Questions