PHP while loop changes the last iteration

I am trying to create 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 explicitly need to remove the last comma. I used to do a while loop with an if statement. However, my database structure makes this situation different.

My PHP code looks like this:

    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'].'"},';
        }
    } 

      

There may be a few missing pieces in the code, but hopefully the context is clear. I am using php variables from previous fetch queries to get data from multiple tables.

In my example, there are several tables corresponding to schools in Texas. I get the first names of each student from multiple schools (or tables). I am trying to apply this information to the JSON output.

The line $jsonfield

shows part of the loop in my code. I'm 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 only apply to parts of my data that are not the last iteration of my loop.

+3


source to share


3 answers


Please don't try to do JSON by hand. Try something like this:



$students = [];

// This would happen in your loop.    
$students[] = array("name" => "John");
$students[] = array("name" => "Alex");
$students[] = array("name" => "Siri");

// Feel free to drop the JSON_PRETTY_PRINT.
echo json_encode(array("students" => $students), JSON_PRETTY_PRINT) . "\n";

// Output:
// {
//     "students": [
//         {
//             "name": "John"
//         },
//         {
//             "name": "Alex"
//         },
//         {
//             "name": "Siri"
//         }
//     ]
// }

      

+5


source


You have two options:

Method 1: rtrim

Use rtrim($jsonfield, ',')

Method 2: implode



Add in $jsonfield

as an array - $jsonfield[]=....

and then use implode(',', $jsonfield)

.


Important:

Moreover, why would you want to generate JSON using a loop? You can use json_encode

.

+2


source


 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'].'"},';
 $i = 0; 
 $countstudents = $getschool->num_rows;                  
if($i+1 < $countstudents){  //if next index is    smaller than the count then add comma else don't and loop will be terminated
    $jsonfield.=','; 
      }
   }
 }

      

+1


source







All Articles