0

I get the following json data from a database:

[{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}]

I'm trying to add all value values together, so: 9.95 + 6.95 ... so that I get 67.6 as result.

I tried the below code, but I am getting 16.9 as repeated values.

for ($i = 0; $i <= $count - 1 ; $i++) {

    $charge = $service[$i]['charge']; 
    $serviceValue = json_decode($charge, true); 
    $totalservice = 0;

    foreach ($serviceValue as $key => $value)      {              
        $totalservice += $value['service_value'];
    }
    echo $totalservice;                
}
2
  • 3
    Set $totalservice = 0; outside for loop. Commented Jan 13, 2017 at 18:46
  • Thanks @u_mulder now it works fine. Thanks alot. Commented Jan 13, 2017 at 18:51

2 Answers 2

1

You can do it like below:-

$jsonObj = json_decode($json); // Decode the JSON to OBJ

// Now loop and find the SUM
$total = 0;
foreach ($jsonObj as $item){
    $total =+ $item->value;
}

// Print the SUM
echo "Sum : $total";

Note:- In your code $totalservice beome 0 every time when loop goes to next iteration and that's why you are getting same value repeated time. So do like (what @u_mulder said) :-

$totalservice = 0;
for ($i = 0; $i <= $count-1 ; $i++) {
.....//rest code
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer @anant . Got the solution by keeping $totalservice=0 outside the loop.
1

I have made the below changes. It works fine.

$totalservice = 0;
for ($i = 0; $i <= $count-1 ; $i++) {
    $charge = $service[$i]['charge']; 
    $serviceValue = json_decode($charge, true); 

    foreach ($serviceValue as $key => $value)      {              
        $totalservice+= $value['service_value'];
    }
    echo $totalservice;                
    }

Thanks for the help

Comments

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.