PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php $tree = [ ['name' => 'Уровень 1', 'id' => 1, 'pid' => 0], ['name' => 'Уровень 1.1', 'id' => 2, 'pid' => 1], ['name' => 'Уровень 1.2', 'id' => 3, 'pid' => 1], ['name' => 'Уровень 1.3', 'id' => 4, 'pid' => 1], ['name' => 'Уровень 2', 'id' => 5, 'pid' => 0], ['name' => 'Уровень 2.1', 'id' => 6, 'pid' => 5], ['name' => 'Уровень 2.2', 'id' => 7, 'pid' => 5], ['name' => 'Уровень 3', 'id' => 8, 'pid' => 0], ['name' => 'Уровень 3.1', 'id' => 9, 'pid' => 8], ['name' => 'Уровень 3.1.1', 'id' => 10, 'pid' => 9], ['name' => 'Уровень 3.1.2', 'id' => 11, 'pid' => 9], ['name' => 'Уровень 1.4', 'id' => 12, 'pid' => 1], ['name' => 'Уровень 2.3', 'id' => 13, 'pid' => 5], ['name' => 'Уровень 3.1.2.1', 'id' => 14, 'pid' => 11], ['name' => 'Уровень 1.4.1', 'id' => 15, 'pid' => 12], ]; function rebuildTree($tree){ foreach ($tree as $key => $node) { $branches[$node['id']] = $node; } $rootNodes = []; foreach ($tree as $node) { if ($node['pid'] === 0) { $rootNodes[] = &$branches[$node['id']]; } else { $branches[$node['pid']]['chld'][] = &$branches[$node['id']]; } } return $rootNodes; } function printTree(array $tree) { $stack = []; $visited = []; $stack[] = [null, $tree]; while (!empty($stack)) { [$parent, $node] = array_pop($stack); if (!in_array($node['id'], $visited)) { $visited[] = $node['id']; if ($parent !== null) { echo str_repeat(' ', 4 * $node['level']) . $node['name'] . PHP_EOL; } if (isset($node['chld'])) { foreach (array_reverse($node['chld']) as $child) { $stack[] = [$node['id'], $child]; } } } } } $arr = rebuildTree($tree); printTree($arr);
Show:  
Copy Clear