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
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.
I read user from the database but I return json to ajax only return the last user because I cant concatenate the json encode.
$myObj = new \stdClass();
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
$myJSON = json_encode($myObj);
}
echo $myJSON;
You are now overwriting $myJson in each iteration. We can also not "concatanate" two jsons (well, we could, but we shouldn't, cause it's laborious..).
Better put everything in one array/object and json_encode() at the very end.
$myObj = new \stdClass();
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
// add objects to that array
$users[] = $myObj;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
Now here are some variants:
If you want everything that your db is returning in this items you could shorten that to:
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
// add the whole item (cast as Object) to that array
$users[] = (Object) $fila;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
If you don't care if the items are objects or arrays you could skip the casting and just add the array to the big array:
$users[] = $fila;
Maybe if you concatenate it as array like this
$myJSON[] = $myObj;
and then after the while
echo json_encode($myJSON);
You just have to collect data to big array and then encode whole array. Also there's no reason for creating new StdObjects instead of usual arrays.
// define empty array
$result = [];
while ($fila = $bd->fila()) {
// add to the array all needed elements one by one
$result[] = [
'NOMBRE' => $fila["NOMBRE"],
'ROLENAME' => $fila["ROLENAME"],
'IDUSER' => $fila["IDUSER"],
];
}
// encode whole result
echo json_encode($result);
The below code has only array like ["a","b","c"] but returns [Object,Object,Object]. The result of which I need to use nested $each loop in ajax success function. Is there any better way to do it?
if($_GET['semValue'])
{
$sem_value = $_GET['semValue'];
try
{
$stmt = $dbConn->prepare("SELECT Semester FROM CourseInfo");
$semArray = array();
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$semArray[] = $row;
}
}
echo json_encode($semArray);
exit();
}
catch(PDOException $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}
You're inserting entire row in main array so it will return multidimensional array instead of array of string.
To get the array of string replace the following lines.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$semArray[] = $row["Semester"];
}
Explanation:
$row would be like this,
$row= Array("semester"=>1);
$row= Array("semester"=>2);
// And so on
If you follow your current code then your final array would be like this,
$semArray = Array ( [0]=> Array("semester"=>1), [1]=> Array("semester"=>2));
So it becomes multidimensional array, that's why we use $row["Semester"] to make it single dimensional array of string/integer values.
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);
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);