Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $servername = "localhost";
- $username = "root";
- $password = "";
- $dbname = "databasename";
- // Create connection
- $conn = new mysqli($servername, $username, $password, $dbname);
- // Check connection
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- $index = array();
- $sql = "SELECT firstname, lastname, ID, parentID FROM table";
- $result = $conn->query($sql);
- while($row = $result->fetch_array()){
- $rows[] = $row;
- }
- // create an index on id
- foreach($rows as $row){
- $index[$row['ID']] = $row;
- }
- // build the tree
- foreach($index as $id => &$row){
- if ($id === 0) continue;
- $parent = $row['parentID'];
- $index[$parent]['children'][] = &$row;
- }
- unset($row);
- // obtain root node
- $index = $index[0]['children'];
- /* free result set */
- $result->close();
- /* close connection */
- $conn->close();
- // output json
- echo json_encode($index, JSON_PRETTY_PRINT);
- [
- {
- "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"
- }
- ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement