0

Hello I have this array and I need the sum of Total:

        (
            [0] => SimpleXMLElement Object
                (
                    [Code] => 1
                    [Total] => 28.56
                )

            [1] => SimpleXMLElement Object
                (
                    [Code] => 2
                    [Total] => 67.99
                )

        )

I tried something like this:

$sum = 0;
foreach($myArray as $key=>$value)
{
   $sum+= $value;
}
echo $sum;

but it returned a number in new line not summing it

The result should be 96.55 Please help!

1
  • 5
    $sum+= $value->Total; Commented Jan 23, 2017 at 11:32

3 Answers 3

2

The array listed looks like object.You can try this:

$sum = 0;
foreach($myArray as $key=>$value)
{
   $sum+= $value->Total;
}
echo $sum;

DEMO USING A SAMPLE DATA

Sign up to request clarification or add additional context in comments.

6 Comments

returns me 0 for first example
@IngusGraholskis you can echo $value->Total; and check what it is printing or can post the sample data.
@IngusGraholskis you can try the added demo.
@IngusGraholskis check what you are missing or post the xml data.
Oh . .. Got it working kinda .. But It show correct answer 2 times in table
|
2

Access the property Total from the object like $sum+= $value->Total;

$sum = 0;
foreach($myArray as $key=>$value)
{
   $sum+= $value->Total;
}
echo $sum;

Comments

0

You can use below code to sum multidimensional array.

echo array_sum(array_map(function($item) { return $tempArray->Total; }, $tempArray));

Here, array_map function will map the $tempArray->Total in multidimensional array.

array_sum will sum the mapped values.

1 Comment

@Ingus Graholskis, in this case you can use array instead of object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.