Advertisement
Guest User

Untitled

a guest
Aug 6th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4. function set_nested_array_value(&$array, $path, &$value, $delimiter = '/')
  5. {
  6. $pathParts = explode($delimiter, $path);
  7. //print_r
  8. $current = &$array;
  9. foreach ($pathParts as $key) {
  10. $current = &$current[$key];
  11. }
  12.  
  13. $backup = $current;
  14. $current = $value;
  15.  
  16. return $backup;
  17. }
  18.  
  19. function pruneTree($array)
  20. {
  21. $result = [];
  22. $i = 0;
  23.  
  24. foreach ($array as $key => $node) {
  25. $r = [];
  26. // set the slug if it exists
  27. if (isset($node['folder'])) {
  28. $r['slug'] = $node['folder'];
  29. unset($node['folder']);
  30. }
  31. $r['text'] = $key;
  32. // set the children through recursion
  33. $r['children'] = pruneTree($node);
  34.  
  35. // when the node does not have slug (ie: DOCUMENTS)
  36. // set the slug of the first child - to match expected results.
  37. if (!isset($r['slug']) && isset($r['children'][0])) {
  38. $r['slug'] = $r['children'][0]->slug;
  39. }
  40. // transform to object - to match expected results.
  41. $result[$i] = (object) $r;
  42. $i++;
  43. }
  44.  
  45. return $result;
  46. }
  47.  
  48. function buildTree($results)
  49. {
  50. $data = [];
  51. foreach ($results as $path) {
  52.  
  53. $r = [];
  54. $v = ['folder' => $path['folder']];
  55. $res = set_nested_array_value($r, $path['path_string'], $v);
  56. $data = array_merge_recursive($data, $r);
  57. }
  58. return $data;
  59. }
  60.  
  61. $dsn = 'mysql:dbname=stackoverflow;host=127.0.0.1';
  62. $user = 'rootornoroot';
  63. $password = '******';
  64. $db = new PDO($dsn, $user, $password);
  65.  
  66. $query = "SELECT * FROM validation_paths";
  67.  
  68. $results = $db->query($query);
  69.  
  70. $r = [
  71. 'children' => pruneTree(buildTree($results))
  72. ];
  73. print_r((object) $r);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement