0

I am retrieving JSON data in array and I sort them into the HTML table. So far it is OK, but I would like to sum the specific values from JSON Response and print the sum of object values.

I have a PHP code which sorting me the data from JSON as following:

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.

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. Sorry I am novice in JSON and PHP and I will thank you for any tip you may give me.

4
  • You mean SUM of price? Commented Jun 12, 2015 at 10:08
  • Is $result->response a JSON ? Commented Jun 12, 2015 at 10:09
  • yes sorry for my English I will try to correct it:) Commented Jun 12, 2015 at 11:23
  • No it is mainly PHP problem, I am already handling the JSON response. Commented Jun 12, 2015 at 11:31

1 Answer 1

2

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}";
Sign up to request clarification or add additional context in comments.

3 Comments

You can add the sum control to the echo =)
Yes you can have also the echo lines let me update it
That is what I looked for. Your code is just simple and works on 100%. Thank you.

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.