如何从json字符串中汇总值?

时间:2017-01-13 18:44:09

标签: php json

我从数据库中获取以下json数据:

[{"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"}]

我试图将所有value值加在一起,所以:9.95 + 6.95 ......这样我就得到了67.6。

我尝试了以下代码,但我的重复值为16.9。

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 个答案:

答案 0 :(得分:1)

你可以这样做: -

onChildAdded

注意: - 每次循环进入下一次迭代时,在代码$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"; beome $totalservice中,这就是为什么你得到相同值重复时间的原因。所以喜欢(@u_mulder所说的): -

0

答案 1 :(得分:1)

我做了以下更改。它工作正常。

$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;                
    }

感谢您的帮助