Valid way to Generate Nested or Complex JSON data using PHP for Flutter

We used to build chrome extension and worked with JSON and Javascript, at that time We have certain ways to generate Nested JSON with PHP but, when We come to Flutter App Development, that causes an error while parsing. After that, We get another way; certainly, a valid way to generate the JSON. We have shown that method in the example below.

  $db = "test_db";
  $host = "localhost";
  $db_user = 'root';
  $db_password = 'root';
  //MySql server and database info

  $link = mysqli_connect($host, $db_user, $db_password, $db);
  //connecting to database

  $json["error"] = false; //boolean output
  $json["errmsg"] = "";
  $json["data"] = array();
  //json output array

  $sql = "SELECT * FROM student_list ORDER BY full_name ASC";
  $res = mysqli_query($link, $sql);
  $numrows = mysqli_num_rows($res);
  if($numrows > 0){
     //check if there is any data
      while($array = mysqli_fetch_assoc($res)){
           array_push($json["data"], $array);

      /* Do not push data like below,
      it will cause error on flutter json prasing. 
      user array_push() function.  

      $datalist = array();
      $x = 1;
      while($array = mysqli_fetch_assoc($res)){
           $datalist[$x] = $array;
      $json["data"] = $datalist;

      $json["error"] = true;
      $json["errmsg"] = "No any data to show.";

  header('Content-Type: application/json');
  // tell browser that its a json data
  echo json_encode($json);


         "full_name":"Anil Chaudhary",
         "address":"Kailali, Nepal",
         "full_name":"Arjun Chaudhary",
         "address":"Chaumala, Nepal",
         "full_name":"John Karki",
         "address":"Pokhara, Nepal",
         "full_name":"Karan Chaudhary",
         "address":"Dang, Nepal",
         "full_name":"Krishna Chaudhary",
         "address":"Kathmandu, Nepal",
         "full_name":"Rabi Shahi",
         "address":"Dhangadhi, Nepal",

In this way, you can generate valid nested JSON with PHP and MySQL.

No any Comments on this Article

Please Wait...