title: PHP MySql select to array
body: <p>I have working code which write result into array but values are doubled. Here is code:</p>
  
  <pre><code>&lt;?php
      $servername = "localhost";
      $username = "root";
      $password = "";
      $dbname = "databasename";
      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn-&gt;connect_error) {
          die("Connection failed: " . $conn-&gt;connect_error);
      } 
      $index = array();
      $sql = "SELECT firstname, lastname, ID, parentID FROM table";
      $result = $conn-&gt;query($sql);
  
      while($row = $result-&gt;fetch_array()){
      $rows[] = $row;
      }
  
      // create an index on id
      foreach($rows as $row){
        $index[$row['ID']] = $row;
      }
  
      // build the tree
      foreach($index as $id =&gt; &amp;$row){
        if ($id === 0) continue;
        $parent = $row['parentID'];
        $index[$parent]['children'][] = &amp;$row;
      }
      unset($row);
  
      // obtain root node
      $index = $index[0]['children'];
  
      /* free result set */
      $result-&gt;close();
      /* close connection */
      $conn-&gt;close();
  
      // output json
      echo json_encode($index, JSON_PRETTY_PRINT);
  </code></pre>
  
  <p>but it produces JSON like this</p>
  
  <pre><code>[
    {
      "0": "Luka",
      "firstname": "Luka",
      "1": "Some",
      "lastname": "Some",
      "2": "287",
      "ID": "287",
      "3": "277",
      "parentID": "277"
  },
  {
      "0": "John",
      "firstname": "John",
      "1": "Test",
      "lastname": "Test",
      "2": "4080",
      "ID": "4080",
      "3": "277",
      "parentID": "277"
    }
  ]
  </code></pre>
  
  <p>Could someone tell me what is wrong with aboove PHP code so it does not produce double records in JSON.
  Thank you</p>