Skip to content

Instantly share code, notes, and snippets.

@rajvanshipradeep15
Created March 29, 2017 06:44
Show Gist options
  • Save rajvanshipradeep15/6cf5f34669c6fbad2f5d80ff1ad5d8bd to your computer and use it in GitHub Desktop.
Save rajvanshipradeep15/6cf5f34669c6fbad2f5d80ff1ad5d8bd to your computer and use it in GitHub Desktop.
<?php
error_reporting( E_ALL );
ini_set('display_errors', 1);
include 'Database.php';
$db = new Database();
$data = $db->getRecords();
$newData = array();
$tree = array();
foreach ($data as $key => $value) {
$newData[$value['Id']] = $value;
}
foreach ($newData as $key => $value) {
if($value['parent_id'] != 0 ) {
$tree[$value['name']] = $newData[$value['parent_id']]['name'];
} else {
$tree[$value['name']] = 'null';
}
}
function parseTree($tree, $root = 'null') {
$return = array();
# Traverse the tree and search for direct children of the root
foreach($tree as $child => $parent) {
# A direct child is found
if($parent == $root) {
# Remove item from tree (we don't need to traverse this again)
unset($tree[$child]);
# Append the child into result array and parse its children
$return[] = array(
'name' => $child,
'children' => parseTree($tree, $child)
);
}
}
return empty($return) ? null : $return;
}
function printTree($tree) {
if(!is_null($tree) && count($tree) > 0) {
echo '<ul>';
foreach($tree as $node) {
echo '<li>'.$node['name'];
printTree($node['children']);
echo '</li>';
}
echo '</ul>';
}
}
$result = parseTree($tree);
printTree($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment