mark5 mark5 - 3 months ago 25
JSON Question

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>';

Answer

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>';
Comments