I am developing in PHP/MS SQL for getting JSON Response.
Code which I wrote is:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$array_res[] = $result; // add result to array
array_push($array_res, array('unidad' => $uni)); // add extra element
$jsonObj = json_encode($array_res); // encode JSON
}
echo $jsonObj;
exit();
This is what I want in result:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null,"unidad":1}]
but the result shows me this:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null},{"unidad":1}]
You're fetching an object. Add $uni to $result first and then add to $array_res:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$result->unidad = $uni;
$array_res[] = $result;
}
Also, you probably want the json_encode() after the loop not in the loop:
echo json_encode($array_res);
Related
I'm trying to GET a JSON format back when I POST a specific ID to my database. As I get more than one result I have multiple rows, which I want to get back. I do get different arrays back, but it is not a valid JSON Format. Instead of
[{...},{...},{...}]
it comes back as
{...}{...}{...}
Therefore the [...] are missing and the arrays are not separated by commas.
My code is down below. The function "getUserBookingsKl" is defined in a different php.
//get user bookings
public function getUserBookingsKl($id) {
//sql command
$sql = "SELECT * FROM `***` WHERE `hf_id`=$id AND `alloc_to`>DATE(NOW()) AND NOT `confirmation`=0000-00-00 ORDER BY `alloc_from`";
//assign result we got from $sql to $result var
$result = $this->conn->query($sql);
// at least one result
if ($result !=null && (mysqli_num_rows($result) >= 1 ))
{
while ($row = $result->fetch_array())
{
$returArray[] = $row;
}
}
return $returArray;
}
...
...
foreach($userdb as $dataset)
{
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
echo json_encode($returnArray);
# return;
}
// Close connection after registration
$access->disconnect();
It looks like you're sequentially emitting the values, not pushing into an array. You need to make an array, push into it, then call json_encode on the resulting structure:
$final = [ ];
foreach ($userdb as $dataset)
{
$returnArray = [ ];
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
$final[] = $returnArray;
}
echo json_encode($final);
Note that it's important here to not use the same variable inside the loop each time through or you're just pushing the same array in multiple times.
Hi every one i am pretty new to programming and my worry is as follows.
I have the following php code where students' averages are calculated and the result filled in an asssociative array. This array should later on be converted to json format.
require_once("functions.inc"); // all my functions are here
$conn = mysqli_connect(DBHOST,DBUSER,DBPASS,DB); // connects to my database
if (!$conn) {
error_log("Cannot connect to MySQL: " .$mysqli->connect_error);
return false;
}
$query = "SELECT distinct exam.student_matricule from exam join student on exam.student_matricule=student.student_matricule where student.class_id=3"; //
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$average=student_average(3,$studentmatricule,1); // this function call calculates students' averages
$stud_averages[$studentmatricule]=$average; //associative array that has **$studentmatricule** as key and **$average** as value
}
foreach($stud_averages as $student => $av)
{
$data=array('student_matricule'=>"$student",'average'=>"$av");
print json_encode($data);
}
My worry now is, print json_encode($data) prints
{"student_matricule":"17A002NA","average":"12.52"}{"student_matricule":"17A001NA","average":"10.53"}{"student_matricule":"17A003NA","average":"12.69"}
But i want something like
[{"student_matricule":"17A002NA","average":"12.52"},{"student_matricule":"17A001NA","average":"10.53"},{"student_matricule":"17A003NA","average":"12.69"}]
Please what should i do?
Thanks in advance!
You're printing single dimensional Array inside loop so it is printing as a JSON
If you want it as a JSON array you need to store it in a multidimensional array like this
$data = [];
foreach($stud_averages as $student => $av)
{
$data[]=array('student_matricule'=>"$student",'average'=>"$av");
}
print json_encode($data); // It prints JSON Array
You are printing every array seperately in foreach loop. You need to add every loop data in a array that defined outside the loop. You can try like this :
$res = array();
foreach($stud_averages as $student => $av)
{
$data=array('student_matricule'=>"$student",'average'=>"$av");
array_push($res, $data);
}
print json_encode($res);
you can also try like this
$data = [];
$std = array();
foreach($stud_averages as $student => $av)
{
$std['student_matricule']= "$student";
$std['average'] ="$av";
}
array_push($data,$std);
print json_encode($data); // It prints JSON Array
i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;
Can anyone explain me how to get the final value assigned to variable after completing executing while loop?
In my below code I wanted to echo the response out of while loop after fetching all the values from the rows.
Because if I put echo out of while loop it only shows 1st record.
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
echo $response;
}
You will get the last rows value into the $response.
Cause: Every time the loop executes will assign value into the variable. But as you echo it you can see all the values as output.
So what you really need to do is storing the values in an array...
$response = array();
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
print_r($response);
If you need further information about this , just let me know.
Since you are doing variable assignment and echo inside while loop, it will not serve your purpose.
You have to do it like below:-
$response = array(); // create an array
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load(); // assign each value to array
}
echo "<pre/>";print_r($response);// print the array
Note:- this array will have all the values now. You can manipulate it in your desired way.Thanks
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
}
echo $response;
Try this:
$response = [];
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
var_dump($response);
I need json response in different array, but below code not give all the result.
while ($row=mysqli_fetch_assoc($result))
{
//$data[]=$row;
$data['id']=$row['id'];
$data['name']=$row['name'];
$data['Latitude']=$row['Latitude'];
$data['Longitude']=$row['Latitude'];
$lat_user=$row['Latitude'];
$long_user=$row['Longitude'];
$res=file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json".
"?units=imperial&origins=$lat,$long&destinations=$latuser,$longuser");
$json_res=json_decode($res);
$data['time']=$json_res->{'rows'}{0}->{'elements'}{0}->{'duration'}->{'text'};
}
echo json_encode($data,true);
You need to save your items into some array, e.g $dataArray at the end of each iteration and after cycle use this array to create json
$dataArray = array();
while ($row=mysqli_fetch_assoc($result))
{
//$data[]=$row;
$data['id']=$row['id'];
$data['name']=$row['name'];
$data['Latitude']=$row['Latitude'];
$data['Longitude']=$row['Latitude'];
$lat_user=$row['Latitude'];
$long_user=$row['Longitude'];
$res=file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json".
"?units=imperial&origins=$lat,$long&destinations=$latuser,$longuser");
$json_res=json_decode($res);
$data['time']=$json_res->{'rows'}{0}->{'elements'}{0}->{'duration'}->{'text'};
$dataArray[] = $data;
}
echo json_encode($dataArray,true);