mark5
mark5

Reputation: 563

PHP Sum up JSON Object value

I know this sounds silly but how do I get the total sum of all the object's total?

My json decode format looks something like this:

Array
(
[results] => Array
    (
        [0] => Array
            (
                [total] => 22   
            )
        [1] => Array
            ( 
                [total] => 10
            )
     )
)   

I've tried using writing something like this but it shows "Trying to get property of non-object in..."

echo 'Array Total<pre>';
$sum = 0;
foreach ( $receipt_data['results'] as $receipt )
{
    $sum += $receipt->total;
}
echo '</pre>';

Upvotes: 2

Views: 3476

Answers (1)

Nikhil Vaghela
Nikhil Vaghela

Reputation: 2096

Try this it's works for you You have array so you need to use array instead of object.

echo 'Array Total<pre>';
$sum = 0;
foreach ( $receipt_data['results'] as $receipt )
{
    $sum += $receipt['total'];
}
echo '</pre>';

Upvotes: 3

Related Questions