Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function set_nested_array_value(&$array, $path, &$value, $delimiter = '/')
- {
- $pathParts = explode($delimiter, $path);
- //print_r
- $current = &$array;
- foreach ($pathParts as $key) {
- $current = &$current[$key];
- }
- $backup = $current;
- $current = $value;
- return $backup;
- }
- function pruneTree($array)
- {
- $result = [];
- $i = 0;
- foreach ($array as $key => $node) {
- $r = [];
- // set the slug if it exists
- if (isset($node['folder'])) {
- $r['slug'] = $node['folder'];
- unset($node['folder']);
- }
- $r['text'] = $key;
- // set the children through recursion
- $r['children'] = pruneTree($node);
- // when the node does not have slug (ie: DOCUMENTS)
- // set the slug of the first child - to match expected results.
- if (!isset($r['slug']) && isset($r['children'][0])) {
- $r['slug'] = $r['children'][0]->slug;
- }
- // transform to object - to match expected results.
- $result[$i] = (object) $r;
- $i++;
- }
- return $result;
- }
- function buildTree($results)
- {
- $data = [];
- foreach ($results as $path) {
- $r = [];
- $v = ['folder' => $path['folder']];
- $res = set_nested_array_value($r, $path['path_string'], $v);
- $data = array_merge_recursive($data, $r);
- }
- return $data;
- }
- $dsn = 'mysql:dbname=stackoverflow;host=127.0.0.1';
- $user = 'rootornoroot';
- $password = '******';
- $db = new PDO($dsn, $user, $password);
- $query = "SELECT * FROM validation_paths";
- $results = $db->query($query);
- $r = [
- 'children' => pruneTree(buildTree($results))
- ];
- print_r((object) $r);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement