3

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.

3 Answers 3

5

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

$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"
//         }
//     ]
// }
Sign up to request clarification or add additional context in comments.

1 Comment

Yup, there is a ready php function to generate json string, no need to manually manipulating json file
2

You have two options:

Method 1: rtrim

Use rtrim($jsonfield, ',')

Method 2: implode

Add to $jsonfield as array - $jsonfield[]=.... and then use implode(',', $jsonfield).


Important:

More than these, why do you want to generate JSON using loop? You can use json_encode function.

Comments

1
 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.=','; 
      }
   }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.