Skip to content

Commit 93af583

Browse files
committed
Merge pull request #86 from dmaksimov/dmaksimov
#85: added tree flattening feature
2 parents d2a95b3 + 82efa9e commit 93af583

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/Collection.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,4 +101,49 @@ protected function getRootNodeId($root)
101101

102102
return $root;
103103
}
104+
105+
/**
106+
* Build a list of nodes that retain the order that they were pulled from
107+
* the database.
108+
*
109+
* @return Collection|static
110+
*/
111+
public function toFlattenedTree()
112+
{
113+
$tree = $this->toTree();
114+
115+
return $tree->flattenTree();
116+
}
117+
118+
/**
119+
* Flatten a tree into a non recursive array
120+
*/
121+
public function flattenTree()
122+
{
123+
$items = [];
124+
125+
foreach ($this->items as $node) {
126+
$items = array_merge($items, $this->flattenNode($node));
127+
}
128+
129+
return new static($items);
130+
}
131+
132+
/**
133+
* Flatten a single node
134+
*
135+
* @param $node
136+
* @return array
137+
*/
138+
protected function flattenNode($node)
139+
{
140+
$items = [];
141+
$items[] = $node;
142+
143+
foreach ($node->children as $childNode) {
144+
$items = array_merge($items, $this->flattenNode($childNode));
145+
}
146+
147+
return $items;
148+
}
104149
}

0 commit comments

Comments
 (0)