0

For example I have this JSON.

[{"rate":3},{"rate":4},{"rate":3},{"rate":5}]

What can I do so I can add all the values inside of it in PHP. Thaanks :)

So this is the code goes srry.

<?PHP
include_once("connection.php");

$query = "SELECT rate FROM tbl_ratings WHERE userID = 10";

$result = mysqli_query($conn, $query);

$json = array();

if(mysqli_num_rows($result)){
    while($row = mysqli_fetch_assoc($result)){
     $json[]=$row;
}
}
mysqli_close($conn);
echo json_encode($json, JSON_NUMERIC_CHECK);
echo array_sum($json, JSON_NUMERIC_CHECK);
?>
3
  • Use the array_sum() function? Commented Aug 9, 2017 at 10:57
  • Can it be possible that you add this all json elements and then send it to php? will it work? Commented Aug 9, 2017 at 10:57
  • Decode the JSON, process the resulting object, encode it back if necessary. Commented Aug 9, 2017 at 10:57

3 Answers 3

1

You don't need to reconfigure your json string to suit the method -- just add array_column().

Code: (Demo)

// these are subarrays containing 1 element each
$json = '[{"rate":3},{"rate":4},{"rate":3},{"rate":5}]';

// decode it to an array    
$array = json_decode($json, true);

// extract the "rate" column values from each subarray and sum them
echo array_sum(array_column($array, 'rate'));

Output:

15

...but honestly, it looks like you have over-complicated the task. Just add it all up using MySQL.

$result = mysqli_query($conn, "SELECT SUM(rate) FROM tbl_ratings WHERE userID = 10");
echo mysqli_fetch_row($result)[0];  //15
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
//Your json decode
$json = json_decode($YourJson);
//summation of all elements
$total = array_sum($jaon);
?>

Comments

0
  1. Your JSON in incorrect. It should have proper square brackets. Before 3, there should be opening square bracket and not {
  2. You should do json_decode()
  3. Use array_sum() to get the sum of all values.

Below is the code:

$json = '{"rates": [3,2,3,5,7]}';
$arr = json_decode($json);
echo array_sum($arr->rates);

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.