简体   繁体   English

来自PHP的JSON数组响应的总和

[英]Sum values from JSON array response by PHP

I am retrieving JSON data in array and I sort them into the HTML table. 我正在检索数组中的JSON数据,并将它们排序到HTML表中。 So far it is OK, but I would like to sum the specific values from JSON Response and print the sum of object values. 到目前为止,还可以,但是我想对JSON Response中的特定值求和并打印对象值的总和。

I have a PHP code which sorting me the data from JSON as following: 我有一个PHP代码,它按如下方式对来自JSON的数据进行排序:

foreach($result->response as $value)
 {

  echo "<tr>";
    echo "<td>" . $value->datetime  . "</td>";
    echo "<td>" . $value->service_type  . "</td>";
    echo "<td>" . $value->destination  . "</td>";
    echo "<td>" . $value->duration  . "</td>";
    echo "<td>" . $value->price  . "</td>";
    echo "</tr>";

 }

I am interested only in values of prices (in JSON Array), I would like to take only the value of prices from JSON and sum the values of prices and give the result number under the table. 我只对价格值感兴趣(在JSON数组中),我只想从JSON中获取价格值,并对价格值求和,并在表格下提供结果编号。

I am trying this without any success: 我正在尝试没有任何成功:

$countprice = $result->response->price;
$totalprice = count($countprice);
echo $totalprice; 

The result is weird number, I know that PHP use "count", but I am not sure how to use it. 结果是奇怪的数字,我知道PHP使用“计数”,但是我不确定如何使用它。 Sorry I am novice in JSON and PHP and I will thank you for any tip you may give me. 抱歉,我是JSON和PHP的新手,如果您给我任何提示,我将非常感谢。

Try this 尝试这个

    <?php

    $sum = 0;
    foreach ($result->response as $value) {
    echo "<tr>";
    echo "<td>" . $value->datetime  . "</td>";
    echo "<td>" . $value->service_type  . "</td>";
    echo "<td>" . $value->destination  . "</td>";
    echo "<td>" . $value->duration  . "</td>";
    echo "<td>" . $value->price  . "</td>";
    echo "</tr>";
    $sum += $value->price;
    }
    echo "sum is {$sum}";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM