title: How to create JSON API service from mysql database in php
body: <p>I have following mysql database table</p>
  
  <pre><code>id | majorFoodName | cropName | foodType  | foodName  | quantity | form 
  1  | Recipe1       | Rice     | Breakfast | Foodname1 | 500+60   | 2000 
  4  | Recipe2       | Rice     | Breakfast | Foodname2 | 500      | 1000
  6  | Recipe1       | Wheat    | Breakfast | Foodname2 | 518      | 1000 
  </code></pre>
  
  <p>I have written following php code to give JSON API output</p>
  
  <pre><code>$sql = "SELECT * FROM food WHERE cropName = 'Rice' AND foodName = 
  'Foodname1' ";
  $result = mysqli_query($connect, $sql);
  $num_rows = mysqli_num_rows($result);
  if ($num_rows &gt; 0) {
      $jsonData = array();
      while ($array = mysqli_fetch_row($result)) {
      $jsonData[] = $array;
    }
  }
  class Emp {
    public $majorFoods = "";    
     }
     $e = new Emp();
     $e-&gt;majorFoods = $jsonData;
     header('Content-type: application/json');
     echo json_encode($e);
  </code></pre>
  
  <p>I am getting following JSON output</p>
  
  <pre><code>{
      "majorFoods": [
          [
          "1",
          "Recipe1",
          "Rice",
          "Breakfast",
          "Foodname1",
          "500+60",
          "2000"
      ]
    ]
  }
  </code></pre>
  
  <p>I need to give following API JSON format for all cropName and all foodName</p>
  
  <pre><code>{
    "Rice": [
                 {
                   "foodName1": {
                          "majorFoodName": "Receipe1",
                          "quantity": "500+60",
                          "form": "2000" }
                   "foodName2": {
                          "majorFoodName": "Receipe2",
                          "quantity": "500",
                          "form": "1000" } 
                   ]
    "Wheat": [
                 {
                   "foodName2": {
                          "majorFoodName": "Receipe1",
                          "quantity": "518",
                          "form": "1000" }
                   ]
  }
  </code></pre>
  
  <p>Kindly help in improving the php code to get desired API JSON response.</p>