Need proper json response - php

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

Related

How to create single JSON for all matching results?

I am fetching data from the database, and while I'm fetching, I check for each result if it matches certain criteria, if it does, I want it to add the row with all the details as a new object inside the same JSON, so that I end up with a single JSON that holds all the matching rows
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (matching criteria){
//add row to the JSON
}
}
Right now I can add each row and echo it, but it overwrites the previous row:
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (matching criteria){
$firstColumn = $result['firstColumn'];
$secondColumn= $result['secondColumn'];
//more columns if necessary. . .
$myObj->firstColumn = $firstColumn ;
$myObj->secondColumn= $secondColumn;
$myJSON = json_encode($myObj);
echo $myJSON;
}
}
you can use PDO::fetch_object for ever row and add them to assoc array/another object and then use the json_encode on it.
something like (pseudocode not tested) it will create json array with object for every row:
$out = [];
while($result = $stmt->fetch(PDO::FETCH_OBJ)
{
if(matching){
$out[] = $result;
}
}
echo json_encode($out);
Try this way create a array assign value to that array with myObj Data and after get collection of array convert into Json object
$data = array(array());
$i = 0;
$j = 0;
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (matching criteria){
$firstColumn = $result['firstColumn'];
$secondColumn= $result['secondColumn'];
//more columns if necessary. . .
$myObj->firstColumn = $firstColumn ;
$myObj->secondColumn= $secondColumn;
$data[i][j]=$firstColumn;
$j++;
$data[i][j]=$secondCoulmn;
$i++;
$j--;
}
}
$myJSON = json_encode($data);
echo $myJSON;

php array to json sting conversion

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

how can produce json array with while in php

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;

PHP While loop for Select Query

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

how to add extra element to array with array_push in PHP?

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

Categories