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);
?>
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
<?php
//Your json decode
$json = json_decode($YourJson);
//summation of all elements
$total = array_sum($jaon);
?>
Your JSON in incorrect. It should have proper square brackets. Before 3, there should be opening square bracket and not {
You should do json_decode()
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);
Related
i stored data by using multiple checkbox in mysql. i want to show this stored data without include comma by using array. but, it is shown as the array was count comma
index.php
include('config.php');
$results = array();
$sql = "select * from assign1 where id='1'";
$run = mysqli_query($mysqli,$sql);
while($row = mysqli_fetch_assoc($run)) {
$results[] = $row['assign']; ?>
<p><?php print_r($results) ?></p>
<?php echo $results[0][0] ."".$results[0][2]."". $results[0][4] ?>
<?php } ?>
In mysql,
In output, i stored no 11, but array is only show 1.
output : 691
Can you try to explode() function:
$results[] = explode(',', $row['assign']);
foreach($results as $result) {
echo $result.'/n';
}
Use explode() to convert from string to array
$a = "1,2,3";
$d = explode(',',$a);
print_r($d);
i want to put comma's in numbers
The output is this which is encoded in json array
[{"total2":"7619627.0000"}]
I want to change the number in this format
[{"total2":"7,619,627"}]
heres the php code
$sql2 = "SELECT SUM(NettoPrice) AS total2 FROM Sales WHERE OrderType = 8";
$result2 = $conn->query($sql2);
// output data of each row
while($row[] = $result2->fetch_assoc()) {
$json = json_encode($row);
}
echo $json;
$conn->close();
?>
With MYSQL 5.5:
SELECT FORMAT(SUM(NettoPrice),0) AS total2;
SQL fiddle
With PHP
number_format('7619627.0000',0);
Use number_format();
$row[count($row)-1]['total2'] = number_format($row[count($row)-1]['total2']);
$json = json_encode($row);
i want to use json result in some calculation but whatever i try it didn't work.
<?php
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2);
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
// "gp_id"=>$row['gp_id'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
//calculate avg rate of specific product
$avg_rate = (int)"total_rate" / (int)"consumer";
echo $avg_rate ;
?>
as you see at the end i try to do some calculation but it didn't work.
this is the output...
[{"total_rate":"18","consumer":"4"}]
Warning: Division by zero in C:\xampp\htdocs\totalrate\highRate.php on line 33
$objJson=json_encode($res); makes json string. For example '{"a":1,"b":2,"c":3,"d":4,"e":5}'. You cannot use it like variables. Its string.
$avg_rate = "total_rate" / "consumer";
Looks like you trying to divide a string with another string.
Try using the array element instead, like:
$avg_rate = $res["total_rate"] / $res["consumer"];
finally i solve the problem ...
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2) or die(mysql_error());
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
"avg_rate"=>$row['total_rate']/ $row['consumer'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
?>
I want to convert selected result into JSON.
Here is my code:
<?php
include("DbConnect.php");
$connection=new DbConnect();
$sth = mysqli_query($connection->_con,"SELECT * FROM account WHERE ac_id='1'");
if($sth){
$rows = array();
while($row = mysqli_fetch_assoc($sth)){
$users = mysqli_query($connection->_con,"SELECT user.user_id,user.name,user.email,ac_detail.ac_id,ac_detail.amount FROM user,ac_detail WHERE ac_detail.ac_id='1' AND user.user_id=ac_detail.user_id");
$usersArray = array();
while($userRow = mysqli_fetch_assoc($users)){
$usersArray[]=$userRow;
}
$a=array("users"=>$usersArray);
//$row["user"]=$usersArray
array_push($row,$a);
$rows[] = $row;
}
echo json_encode(array('data'=>$rows));
}else{
echo json_encode(array('message'=>'error - 2'));
}
?>
By executing this code it generate JSON like :
{"data":[{"ac_id":"1","user_id":"2","title":"Travel","ac_for":"Traveling","required_amount":"50","current_amount":"0","initial_date":"2014-11-11","final_date":"2014-11-14","is_shared":"1","status":"1","0":{"users":[{"user_id":"2","name":"Muhammad Imran","email":"macrotechnolgies#gmail.com","ac_id":"1","amount":"0"},{"user_id":"3","name":"Muhammad Imran","email":"macrotecholgies#gmail.com","ac_id":"1","amount":"0"}]}}]}
But i don't want "0"{"user::...}
How it should be (Expected Results) :
{"data":[{"ac_id":"1","user_id":"2","title":"Travel","ac_for":"Traveling","required_amount":"50","current_amount":"0","initial_date":"2014-11-11","final_date":"2014-11-14","is_shared":"1","status":"1","users":[{"user_id":"2","name":"Muhammad Imran","email":"macrotechnolgies#gmail.com","ac_id":"1","amount":"0"},{"user_id":"3","name":"Muhammad Imran","email":"macrotecholgies#gmail.com","ac_id":"1","amount":"0"}]}]}
Thanks in advance
You're doing:
while($row = mysqli_fetch_assoc($sth)){
[...snip...]
array_push($row,$a);
The while line creates an array $row, which you then use parts of to create $a. You then push that $a BACK onto the original $row array. But $row is an associative array already, so the pushed $a gets key 0.
Since you're now mixing an associative array (non-numeric keys) with a numeric-keyed array (the push operation), PHP MUST add the numeric key to your pushed item: You can't have an element in an array WITHOUT a key.
Then, since JS doesn't allow actual JS arrays ([]) to have non-numeric keys, the whole thing has to get converted into an object ({}).
What you probably want is something more like:
while($row = ...) {
... build $a ...
array_push($row['users'], $a);
instead.
Why don't you in stead array_push($row,$a) try following:
<?php
include("DbConnect.php");
$connection=new DbConnect();
$sth = mysqli_query($connection->_con,"SELECT * FROM account WHERE ac_id='1'");
if($sth){
$rows = array();
while($row = mysqli_fetch_assoc($sth)){
$users = mysqli_query($connection->_con,"SELECT user.user_id, user.name, user.email, ac_detail.ac_id, ac_detail.amount FROM user,ac_detail WHERE ac_detail.ac_id='1' AND user.user_id=ac_detail.user_id");
$usersArray = array();
while($userRow = mysqli_fetch_assoc($users)){
$usersArray[]=$userRow;
}
// here comes the change
// $a = array("users"=>$usersArray);
// //$row["user"]=$usersArray
// array_push($row,$a);
$row['users'] = $usersArray;
$rows[] = $row;
}
echo json_encode(array('data'=>$rows));
}else{
echo json_encode(array('message'=>'error - 2'));
}
This should work. Dont have sample data to test it.
I am having an issue with how I am converting my php array into a JSON object. No matter what I try, I either print everything out as multiple objects or it comes out as null.Wrapping it in pre tags, here is the closest that I got it:
My code:
$content = mysqli_query($dbcon,
"SELECT title, last_name AS lastname
FROM revision, field_last_name
WHERE vid = entity_id;"
);
echo "<pre>";
while($row = mysqli_fetch_array($content))
{
print json_encode($row);
print '<br/>';
}
echo "</pre>";
My output:
{"0":"John Apple","title":"John Apple","1":"Apple","lastname":"Apple"}
{"0":"Kumar Patel","title":"Kumar Patel","1":"Patel","lastname":"Patel"}
{"0":"Michaela Quinn","title":"Michaela Quinn","1":"Quinn","lastname":"Quinn"}
{"0":"Peyton Manning","title":"Peyton Manning, MD","1":"Manning","lastname":"Manning"}
{"0":"John Doe","title":"John Doe","1":"Doe","lastname":"Doe"}
{"0":"Jane Lee","title":"Jane Lee","1":"Lee","lastname":"Lee"}
{"0":"Dan McMan","title":"Dan McMan","1":"McMan","lastname":"McMan"}
{"0":"Yu Win","title":"Yu Win","1":"Win","lastname":"Win"}
My two questions are:
1) Why is there a "0":"John Apple" and a "1":"Apple" when all I want is "title":"John Apple" and "lastname":"Apple" in my object?
2) Why is everything displaying as multiple objects?
Thanks!
---EDIT---
$arr = array()
echo "<pre>";
while($row = mysqli_fetch_assoc($content))
{
$arr[] = $row;
}
print $arr;
echo "</pre>";
field_last_name is your table name? can you distinguish each column name prefix by table name like revision.title in your query and get all data in a single array and then json_encode it?
$content = mysqli_query($dbcon,
"SELECT title, last_name AS lastname
FROM revision, field_last_name
WHERE vid = entity_id;"
);
$arr = array();
echo "<pre>";
while($row = mysqli_fetch_assoc($content))
{
$arr[] = $row;
}
print_r(json_encode($arr));
echo "</pre>";
Change this:
while($row = mysqli_fetch_array($content))
{
print json_encode($row);
print '<br/>';
}
To this:
$row = mysqli_fetch_assoc($content);
json_encode($row);
...because you're printing out multiple objects. If you want a single object which is an array, you need to append the results of mysql_fetch_assoc (see other answer covering field names vs positions) to an array, then json_encode the array in one shot. Example:
$myarray = array();
while($row = mysqli_fetch_assoc($content))
{
$myarray[] = $row;
print '<br/>';
}
print json_encode($myarray);