Advertisement
Guest User

Untitled

a guest
Mar 2nd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. <?php
  2. $servername = "localhost";
  3. $username = "root";
  4. $password = "";
  5. $dbname = "databasename";
  6. // Create connection
  7. $conn = new mysqli($servername, $username, $password, $dbname);
  8. // Check connection
  9. if ($conn->connect_error) {
  10. die("Connection failed: " . $conn->connect_error);
  11. }
  12. $index = array();
  13. $sql = "SELECT firstname, lastname, ID, parentID FROM table";
  14. $result = $conn->query($sql);
  15.  
  16. while($row = $result->fetch_array()){
  17. $rows[] = $row;
  18. }
  19.  
  20. // create an index on id
  21. foreach($rows as $row){
  22. $index[$row['ID']] = $row;
  23. }
  24.  
  25. // build the tree
  26. foreach($index as $id => &$row){
  27. if ($id === 0) continue;
  28. $parent = $row['parentID'];
  29. $index[$parent]['children'][] = &$row;
  30. }
  31. unset($row);
  32.  
  33. // obtain root node
  34. $index = $index[0]['children'];
  35.  
  36. /* free result set */
  37. $result->close();
  38. /* close connection */
  39. $conn->close();
  40.  
  41. // output json
  42. echo json_encode($index, JSON_PRETTY_PRINT);
  43.  
  44. [
  45. {
  46. "0": "Luka",
  47. "firstname": "Luka",
  48. "1": "Some",
  49. "lastname": "Some",
  50. "2": "287",
  51. "ID": "287",
  52. "3": "277",
  53. "parentID": "277"
  54. },
  55. {
  56. "0": "John",
  57. "firstname": "John",
  58. "1": "Test",
  59. "lastname": "Test",
  60. "2": "4080",
  61. "ID": "4080",
  62. "3": "277",
  63. "parentID": "277"
  64. }
  65. ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement