From ca678b31ce5e6784ef6070dcb496ce01684a1eec Mon Sep 17 00:00:00 2001 From: David Maksimov Date: Wed, 24 Feb 2016 22:55:52 -0600 Subject: [PATCH 1/2] Added a way to retrieve a list of nodes from tree --- src/Collection.php | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/Collection.php b/src/Collection.php index 38815d4..fa32d0a 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -101,4 +101,49 @@ protected function getRootNodeId($root) return $root; } + + /** + * Build a list of nodes that retain the order that they were pulled from + * the database. + * + * @return Collection|static + */ + public function toList() + { + $tree = $this->toTree(); + + return $tree->flattenTree(); + } + + /** + * Flatten a tree into a non recursive array + */ + public function flattenTree() + { + $items = []; + + foreach ($this->items as $node) { + $items = array_merge($items, $this->flattenNode($node)); + } + + return new static($items); + } + + /** + * Flatten a single node + * + * @param $node + * @return array + */ + protected function flattenNode($node) + { + $items = []; + $items[] = $node; + + foreach ($node->children as $childNode) { + $items = array_merge($items, $this->flattenNode($childNode)); + } + + return $items; + } } \ No newline at end of file From 82efa9ef50dfa9388b51334692bba6cc759c56f2 Mon Sep 17 00:00:00 2001 From: David Maksimov Date: Thu, 25 Feb 2016 00:00:00 -0600 Subject: [PATCH 2/2] Renamed toList method to toFlattenedTree --- src/Collection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Collection.php b/src/Collection.php index fa32d0a..312a2b5 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -108,7 +108,7 @@ protected function getRootNodeId($root) * * @return Collection|static */ - public function toList() + public function toFlattenedTree() { $tree = $this->toTree();