I am trying to generate a JSON file from PHP. So far I have the following output:
"students":[
{"name": "John"},
{"name": "Alex"},
{"name": "Siri"},
]
There is a comma after each student, when I clearly have to remove the final comma. Normally I would perform a while loop with an if statement. However, my database structure makes this situation different.
My PHP code looks like so:
while ($getschools = $schools->fetch_assoc()){
$findschools = $dbcon->query("SELECT *
FROM school_".$getstate['texas']."
WHERE students = '".$studentGPA['best']."'");
while ($beststudents = $findschools->fetch_assoc()){
$jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
}
}
The code might have a few missing parts, but hopefully the context is clear. I am using php variables from previous fetch requests to acquire data from multiple tables.
In my example there are multiple tables corresponding to the schools in Texas. I am getting the firstnames of every student from those multiple schools (or tables). I am attempting to apply this information to a JSON output.
The $jsonfield line shows the loop portion of my code. I am trying to figure out how to implement a code like this in my example:
$i = 0;
$countstudents = $getschools->num_rows;
if ($i < $countstudents){
$jsonfield.=',';
}
This way my commas are only applied to the parts of my data that are not the final iteration of my loop.