put comma in numbers on json array using php - php

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);

Related

Adding the integer values inside JSON using PHP

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);

JSON encodes cyryllic as a null

I have MYSQL table with Cyrillic symbols.
This is my MYSQL table
And i use PHP to get MYSQL result and encode it to JSON.
<?php
include 'connection.php';
$array_to_json = array();
$query = "SELECT * FROM online";
$result = mysqli_query($link, $query);
mysqli_set_charset("utf8");
while($row = $result->fetch_assoc()) {
$row_array['parameters'] = $row['parameters'];
$row_array['Descriptions'] = $row['Descriptions'];
$row_array['units'] = $row['units'];
array_push($array_to_json, $row_array);
}
echo json_encode($array_to_json, JSON_UNESCAPED_UNICODE);
$result->close();
?>
And as a result i have got null.
JSON returns null
What do i do wrong?
Did you try using
$row_array['parameters'] = base64_encode($row['parameters']);
$row_array['Descriptions'] = base64_encode($row['Descriptions']);
$row_array['units'] = base64_encode($row['units']);
array_push($array_to_json, $row_array);
recheck your table structure and ensure that there is no extra blank space
for instance:
$row['Descriptions ']
instead of:
$row['Descriptions'];

how i can use JSON result in calculation in php

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;
?>

Php append value to an exsisting array

Hi I need to add some value-key pair to an array which is the output of mysql query. Below is the code,
$query = "select TITLE,DESCRIPTION from TABLE where ID='1234'";
$result = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($result);
if($numrows>0)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$myArray[] = $row;
}
}
echo json_encode($myArray);
Giving me the result like
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION."}]
Now I need to to add an another key-value pair to generate the json output like,
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION.","URL":"imgname.jpg"}]
So I added the code
$myArray["URL"]="imgname.jpg";
echo json_encode($myArray);
But giving me the output like,
{"0":{"TITLE":"Chef Special","DESCRIPTION":"Grilled Salmon and crab."},"URL":"imgname.jpg"}
Is there anything wrong with above code.
check your data with
var_dump($myArray);
and you will find, that it is a 2-dimensional array. you'd have to add your data with
$myArray[0]["URL"] = "imgname.jpg";
If you have to add after encoding it, reverse with:
$a = json_decode($myArray,true)
add a new pair of key, value with $a['URL'] = "imgname.jpg" and then encode again.

PHP - MySQL results to JSON

I'm trying to understand how to convert MySQL results to a JSON format so that I can then use this JSON later on with Javascript to build a HTML table. However my code just produces lot's of null values and I don't yet understand why.
$result = mysqli_query($con, "SELECT * FROM Customers");
$test = json_encode($result);
print $test;
Output:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
I have, for example, fields such as "CustomerID" and "Name", and even they don't show up in the JSON result.
What am I doing wrong?
Thanks
$result = mysqli_query($con, "SELECT * FROM Customers");
while($row = mysqli_fetch_assoc($result))
$test[] = $row;
print json_encode($test);

Categories