read.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. include '../connection.php';
  3. try {
  4. $statement = $db->prepare('select * from list order by lft asc');
  5. if(!$statement->execute()) {
  6. throw new Exception(implode(', ', $statement->errorInfo()));
  7. }
  8. // fetch the flat result set from the database
  9. $lists = $statement->fetchAll(PDO::FETCH_ASSOC);
  10. // convert list result set to nested tree structure.
  11. // create a dummy root node that will be the base of our tree structure
  12. $root = array(
  13. // all nodes in the result set should fall within these left/right bounds
  14. 'lft' => 0,
  15. 'rgt' => PHP_INT_MAX,
  16. 'children' => array()
  17. );
  18. $listStack = array(&$root);
  19. $listCount = count($lists);
  20. for($i = 0; $i < $listCount; $i++) {
  21. $list = &$lists[$i];
  22. $parent = &$listStack[count($listStack) - 1];
  23. while($list['rgt'] > $parent['rgt']) {
  24. // if the current list is not a child of parent, pop lists off the stack until we get to a list that is its parent
  25. array_pop($listStack);
  26. $parent = &$listStack[count($listStack) - 1];
  27. }
  28. // add the node to its parent node's "children" array
  29. $parent['children'][] = &$list;
  30. if($list['rgt'] - $list['lft'] > 2) { // if the node has children
  31. $list['expanded'] = "1"; // nodes that have children are expanded by default
  32. $list['children'] = array();
  33. $listStack[] = &$list; // push the node on to the stack
  34. } else if(empty($list['leaf'])) {
  35. // for non leaf nodes that do not have any children we have to set "loaded" to true
  36. // This prevents the TreeStore from trying to dynamically load content for these nodes when they are expanded
  37. $list['loaded'] = "1";
  38. unset($list['leaf']); // no need to return "leaf: null" to the client for non leaf nodes
  39. }
  40. }
  41. // remove properties that are not needed by the UI (lft and rgt)
  42. function removeTreeProperties(&$list) {
  43. unset($list['lft']);
  44. unset($list['rgt']);
  45. if(isset($list['children'])) {
  46. foreach($list['children'] as &$child) {
  47. removeTreeProperties(&$child);
  48. }
  49. }
  50. }
  51. removeTreeProperties(&$root);
  52. $jsonResult = array(
  53. 'success' => true,
  54. 'children' => $root['children']
  55. );
  56. } catch(Exception $e) {
  57. $jsonResult = array(
  58. 'success' => false,
  59. 'message' => $e->getMessage()
  60. );
  61. }
  62. echo json_encode($jsonResult);
  63. ?>