-
Notifications
You must be signed in to change notification settings - Fork 1
/
NavTree.php
54 lines (46 loc) · 1.3 KB
/
NavTree.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
class NavTree
{
protected $tree;
public function __construct($data)
{
$this->tree = $this->buildTree($data, 'parentId', 'id');
}
protected function buildTree($flat, $pidKey, $idKey = null)
{
$grouped = array();
foreach ($flat as $sub){
$grouped[$sub[$pidKey]][] = $sub;
}
$fnBuilder = function($siblings) use (&$fnBuilder, $grouped, $idKey) {
foreach ($siblings as $k => $sibling) {
$id = $sibling[$idKey];
if(isset($grouped[$id])) {
$sibling['children'] = $fnBuilder($grouped[$id]);
}
$siblings[$k] = $sibling;
}
return $siblings;
};
$tree = $fnBuilder($grouped[0]);
return $tree;
}
private function internalRender($nodes)
{
echo "<ul>";
foreach($nodes as $node) {
echo "<li>{$node['name']}";
if (isset($node['children'])) {
$this->internalRender($node['children']);
}
echo "</li>";
}
echo"</ul>";
}
public function render()
{
echo '<nav>';
$this->internalRender($this->tree);
echo '</nav>';
}
}