Currently, I am making an API and I want the data in JSON format. But I am not able to get it. It is coming in normal form. But how to convert it into JSON. If I am writing json_encode($response) outside the loop then I am getting the data in json format but only one data.
If i wriing the json encode inside the loop then i am getting all the data but not in JSON form. How to solve this. I am not able to get the perfect solution for ths question.
$tsym = strtolower($_REQUEST['tsym']);
$time = strtolower($_REQUEST['time']);
$mil = $time;
$seconds = $mil / 1000;
$normal_date = date("Y-m-d H:i:s", $seconds);
$sql = "SELECT * FROM `forex` where pair='".$tsym."' and date >= '".$normal_date."' order by date limit 0,10";
$result = mysqli_query($conn, $sql);
$response = array();
while($rows = mysqli_fetch_assoc($result)){
$from_sym = $rows['pair'];
//if(!isset($response[$from_sym]))
{
$response[$from_sym] = $rows;
//echo json_encode($response, true);
//}
print_r( json_encode($response)); //this prints all the data but not
in json form
}
print_r( json_encode($response)); //this prints single data but in
json form
I want all the data but in json form. how to get it? Thank you for the help.
I want data like this:
{
"CHFJPY": {
"id": "33",
"pair": "CHFJPY",
"date": "2018-04-22 20:42:21",
"price": "110.413",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "75",
"pair": "CHFJPY",
"date": "2018-04-22 20:42:29",
"price": "110.413",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "117",
"pair": "CHFJPY",
"date": "2018-04-23 11:25:47",
"price": "110.585",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "159",
"pair": "CHFJPY",
"date": "2018-04-23 12:34:54",
"price": "110.816",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "201",
"pair": "CHFJPY",
"date": "2018-04-23 12:35:04",
"price": "110.825",
"change_rate": "0",
"fetched": "1"
}
}
But i am getting only one data.
You have to append your row to the final array $response in your while loop
$response = array();
while($rows = mysqli_fetch_assoc($result)){
$from_sym = $rows['pair'];
$res[$from_sym] = $rows;
$response[] = $res;
}
print_r(json_encode($response));
You need to move the json_encode into the outside of while loop
<?php
$tsym_escaped = mysqli_real_escape_string($conn, $_REQUEST['tsym']);
$date = date("Y-m-d H:i:s", $_REQUEST['time']/1000);
$sql = sprintf(
"SELECT * FROM `forex` WHERE `pain`='%s' AND `date`>='%s' ORDER BY `date` LIMIT 0,10",
$tsym_escaped,
$date
);
$result = mysqli_query($conn, $sql);
$response = array();
while($row = mysqli_fetch_assoc($result)){
$response[$row['pair']] = $row;
}
echo json_encode($response);
Also, the way you're passing the data into the SQL query is insecure and can lead into a SQL injection.
is not clear why you have not json so .. in more clear way try
while($rows = mysqli_fetch_assoc($result)){
$response[$rows['pair']] = $rows;
}
$myJSON = json_encode($response);
var_dump($myJSON);
this should buil a $reponse array with the related vleus for each 'pair' index
but could be you need all the rows result so try
while($rows = mysqli_fetch_assoc($result)){
$response[] = $rows;
}
$mySecondJSON = json_encode($response);
var_dump($mySecondJSON);
or
while($rows = mysqli_fetch_assoc($result)){
$response[] = $rows['pair'];
}
$myOtherJSON = json_encode($response);
var_dump($myOtherJSON);
Related
I need to generate the following JSON from a PHP loop and SQL DB but I'm having trouble:
[
{
"ItemName": "Websites1",
"Websites1": [
{
"0": "1",
"ID": "1",
"1": "Essential",
"WebsiteName": "Essential 1",
"2": "EI",
"WebsiteCode": "EI"
},
{
"0": "2",
"ID": "2",
"1": "Icon Ibiza",
"WebsiteName": "Icon 1",
"2": "IC",
"WebsiteCode": "IC"
},
{
"0": "3",
"ID": "3",
"1": "So Ibiza",
"WebsiteName": "So 1",
"2": "SO",
"WebsiteCode": "SO"
}
]
},
{
"ItemName": "Websites2",
"Websites2": [
{
"0": "1",
"ID": "1",
"1": "Essential Ibiza",
"WebsiteName": "Essential 2",
"2": "EI",
"WebsiteCode": "EI"
},
{
"0": "2",
"ID": "2",
"1": "Icon Ibiza",
"WebsiteName": "Icon 2",
"2": "IC",
"WebsiteCode": "IC"
},
{
"0": "3",
"ID": "3",
"1": "So Ibiza",
"WebsiteName": "So 2",
"2": "SO",
"WebsiteCode": "SO"
}
]
}
]
I have the relevant data being returned from the DB into PHP fine but I can't work out how to generate the relevant key value pairs and nesting using PHP loops. The code I have so far is:
$this->db->sql = "SELECT ID AS ID, WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$response = array();
$json = array();
while ($row = $this->db->row_read($rs)) {
$json["ID"] = $row["ID"];
$json["SelectText"] = $row["SelectText"];
$json["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites1"] = $json;
}
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json2 = array();
while ($row = $this->db->row_read($rs)) {
$json2["ID"] = $row["ID"];
$json2["SelectText"] = $row["SelectText"];
$json2["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites2"] = $json2;
}
return '[' . json_encode($response) . ']';
I'm obviously doing something very wrong as I only end up with one row for each query. The key value pairs are being overwritten with each loop. Also the nesting isn't correct. Sorry for such a dumb question but I've been trying to figure this out from info online and am stuck.
Thanks,
Noon.
EDIT - Managed to fix this using the annswer provided by Anushil Nandan below but the PHP needed a few extra tweaks to get the required format as folows:
// -----------------------------------------------------------------------------------------------
// BANNERMANGEMENTFORM
function bannerManagementJson($JsonItem) {
$this->db->connect();
$response = array();
//Generate Websites drop-down
$SqlStr = "SELECT WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$response[] = $this->retrieveFormElementJson($SqlStr,'Websites',1);
//Generate Clients drop-down
$SqlStr = "SELECT ClientName AS SelectText, ID AS SelectValue FROM Banners_BannerClients ORDER BY ClientName";
$response[] = $this->retrieveFormElementJson($SqlStr,'Clients',2);
return json_encode($response);
}
// -----------------------------------------------------------------------------------------------
// RETRIEVEFORMELEMENTJSON
function retrieveFormElementJson($SqlStr,$ElementName,$SelectListNo) {
$this->db->sql = $SqlStr;
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json = array();
while ($row = $this->db->row_read($rs)) {
$json[] = $row;
}
$arrayResponse = array("ItemName"=>$ElementName, "SelectList" . $SelectListNo=>$json);
}
return $arrayResponse;
}
your array is being overridden every time it's entering while loop
try:
$json1[] = array();
$json2[] = array();
$this->db->sql = "SELECT ID AS ID, WebsiteName AS SelectText, WebsiteCode AS SelectValue FROM Banners_Websites ORDER BY WebsiteName";
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$response = array();
$json[] = array();
while ($row = $this->db->row_read($rs)) {
$json[]["ID"] = $row["ID"];
$json[]["SelectText"] = $row["SelectText"];
$json[]["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites1"] = $json;
}
$rs = $this->db->query($this->db->sql);
if ($this->db->row_count != 0) {
$json2[] = array();
while ($row = $this->db->row_read($rs)) {
$json2[]["ID"] = $row["ID"];
$json2[]["SelectText"] = $row["SelectText"];
$json2[]["SelectValue"] = $row["SelectValue"];
//$json[] = $row;
}
$response["Websites2"] = $json2;
}
return '[' . json_encode($response) . ']';
I'm new to php and am trying to encode 2 arrays together into one JSON object.
Currently this is the JSON output:
{
"image_link": "some url",
"zoomin_level": "8",
"zoomout_level": "18.5",
"position_lat": "32.913105",
"position_long": "-117.140363",
}
What I like to achieve is the following:
{
"image_link": "some url",
"zoomin_level": "2",
"zoomout_level": "15",
"position_lat": "32.9212",
"position_long": "-117.124",
"locations": {
"1": {
"image_link": "some url",
"name": "Name",
"lat": 32.222,
"marker_long": -112.222
},
"2": {
"image_link": "some url",
"name": "Name",
"lat": 32.222,
"marker_long": -112.222
}
}
}
This is similar to the question asked here: PHP json_encode multiple arrays into one object
However mine is a bit different because I like to add the 2nd array as part of a key-value part within the 1st array.
Here's my php code:
$sql = "select * from first_table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$rowCount = $result->num_rows;
$index = 1 ;
$newArray = [];
while($row =mysqli_fetch_assoc($result))
{
$sqlnew = "select * from second_table";
$resultnew = mysqli_query($connection, $sqlnew) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$jsonData = array();
$rowCountnew = $resultnew->num_rows;
$indexnew = 1;
if ($rowCountnew >0)
{
while($rownew =mysqli_fetch_assoc($resultnew))
{
$locations[$indexnew] = array("image_link" => $rownew['image_link'], "name" => $rownew['name'], "position_lat" => doubleval($rownew['position_lat']), "position_long" => doubleval($rownew['position_long']) );
++$indexnew;
}
}
$newArray[$row['map_type']] = $row['map_value'];
}
echo json_encode($newArray);
Not knowing the proper syntax, I tried to perform the following which resulted in garbage: echo json_encode($newArray, "locations" =>$locations);
Try:
$newArray['locations'] = $locations;
echo json_encode ($newArray);
How do i encode two arrays that retrieves data from 2 different table in my database and encode it in 1 json response
Here is my php
$sql = "select * from schedule;";
$sql1 = "select * from matches;";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$result1 = mysqli_query($con,$sql1);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("n_name"=>$row[1],"start"=>$row[4],"end"=>$row[5],"venue"=>$row[6]));
}
$data= array();
while($row=mysqli_fetch_array($result1))
{
array_push($data, array("teamone"=>$row[1], "teamtwo"=>$row[2], "s_name"=>$row[10]));
}
echo json_encode (array("server_response"=>$response, $data));
mysqli_close($con);
?>
What i want is something like this
{
"server_response": [{
"n_name": null,
"start": "2016-11-09 00:00:00",
"end": "2016-11-16 00:00:00",
"venue": "aaaaaa",
"teamone": "aaa",
"teamtwo": "bbb",
"s_name": ""
}]
}
Instead i get something like this
{
"server_response": [{
"n_name": null,
"start": "2016-11-09 00:00:00",
"end": "2016-11-16 00:00:00",
"venue": "aaaaaa"
}],
"0": [{
"teamone": "aaa",
"teamtwo": "bbb",
"s_name": ""
}]
}
Can someone help me. Thanks!
$response = array();
while($row=mysqli_fetch_array($result))
{
$response['server_response']["n_name"] = $row[1];
$response['server_response']["start"] = $row[4];
$response['server_response']["end"] = $row[5];
$response['server_response']["venue"] = $row[6];
}
while($row=mysqli_fetch_array($result1))
{
$response['server_response']["teamone"] = $row[1];
$response['server_response']["teamtwo"] = $row[2];
$response['server_response']["s_name"] = $row[10];
}
echo json_encode ($response);
echo json_encode (array("server_response"=>array_merge($response, $data)));
or
echo json_encode (array("server_response"=>$response + $data)); // if you run the risk of same key existing in both arrays
I want to show percent of department depend on date in c3js chart with timeseries.
I have four department id, and I query the result like this.
$dept_id_arr = array();
$date_arr = array();
$percent_arr = array();
$sql = ........;
$rsl = mysql_query($sql);
while($get = mysql_fetch_assoc($rsl)){
$date_arr[] = $get['date'];
$dept_id_arr[] = $get['department_id'];
$percent_arr[] = $get['total_percent'];
}
When I print this data with var_dump(), I got like this,
string(66) "["2015-11-17","2015-11-17","2015-11-18","2015-11-20","2015-11-23"]"
string(22) "["1","3","1","1","2"]"
string(46) "["0.5700","0.0000","0.5700","0.0000","0.5700"]"
I want to change that value to like this,
[{
"date": "2015-11-17",
"department1": "0.5",
"department2": "0.9",
"department3": "4",
"department4": "3",
}, {
"date": "2015-11-18",
"department1": "0.5",
"department2": "0",
"department3": "0",
"department4": "0",
}, {
"date": "2015-11-19",
"department1": "0.5",
"department2": "0.3",
"department3": "5",
"department4": "2",
}]
because I need to show that data in c3js chart. But I have problem, when I change data to that format because of some date are same in array.
You can do all the things by this code:
<?php
$date = ["2015-11-17","2015-11-17","2015-11-18","2015-11-20","2015-11-23"];
$departmeent = ["1","3","1","1","2"];
$percentage = ["0.5700","0.0000","0.5700","0.0000","0.5700"];
$array = array();
for($i=0; $i<5;$i++)
{
if(array_key_exists($date[$i], $array))
{
$array[$date[$i]]['department'.$departmeent[$i]]= $departmeent[$i];
$array[$date[$i]]['per'.$departmeent[$i]]= $percentage[$i];
}
else
{
$array[$date[$i]] = array('department'.$departmeent[$i] => $departmeent[$i],
'per'.$departmeent[$i] => $percentage[$i]) ;
}
}
echo var_dump($array["2015-11-17"]["department1"]);
echo '<br><br><br><br><br><br>'.json_encode($array);
?>
I have developed an api which will post some data in json format to be used in an android app. However I am getting json parsing error. I am new to this whole json thing so unable to understand what the error means.
This is my json encoded output that the php backend generates
{
"data": [
{
"id": "2",
"name": "Rice",
"price": "120",
"description": "Plain Rice",
"image": "6990_abstract-photo-2.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
}
]
}{
"data": [
{
"id": "4",
"name": "Dal",
"price": "5",
"description": "dadadad",
"image": "",
"time": "20 mins",
"catagory": "Dinner",
"subcat": ""
}
]
}{
"data": [
"catagory": "Soup"
]
}
This is the error the online json parser gives
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data
What is actually wrong here? Could you please provide me with the correct json output for the following data?
This should clear it up
$main = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'"; //Prepare login query
$value = $DBH->query($query1);
if($row1 = $value->fetch(PDO::FETCH_OBJ))
{
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
You shouldn't create your json string by hand. Create your array structure, then finally invoke json_encode() at the end.
$data = array();
try
{
$query = "SELECT category FROM category"; // select category FROM category? what?
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($value->rowCount() > 0) {
$data[] = array('data' => $value->fetch(PDO::FETCH_ASSOC));
}
else {
$sub = array('category' => $row['category']);
$data[] = array('data' => $sub);
}
}
$result->closeCursor();
$DBH = null;
echo json_encode($data); // encode at the end
}
catch(PDOException $e)
{
print $e->getMessage ();
die();
}