bartko-s / stefano-tree

Framework agnostic Nested Set (MPTT) implementation for PHP
https://bartko-s.github.io/stefano-tree
BSD 3-Clause "New" or "Revised" License
28 stars 8 forks source link

Add helper function "Flat to Nested" #12

Closed TNAJanssen closed 6 years ago

TNAJanssen commented 6 years ago

Hi,

Did you already created something to retrieve the complete tree structure back instead of a flat array?

Thanks!

bartko-s commented 6 years ago

You can try.

public function flatToNested(
        array $flatTree,
        $level = null,
        $startPos = 0,
        array &$result = array(),
        string $levelName = 'level'): array
    {
        $total = count($flatTree);
        $first = true;

        for ($pos = $startPos; $pos < $total; ++$pos) {
            $item = $flatTree[$pos];

            if (null === $level) {
                $level = $item[$levelName];
            }

            if (!array_key_exists('_children', $item)) {
                $item['_children'] = array();
            }

            if ($level == $item[$levelName]) {
                $result[] = $item;
                $first = true;
            } elseif (($level + 1) == $item[$levelName] && true == $first) {
                $children = array($item);
                self::flatToNested($flatTree, $item[$levelName], $pos + 1, $children, $levelName);
                $result[count($result) - 1]['_children'] = $children;
                $first = false;
            } elseif ($level > $item[$levelName]) {
                break;
            }
        }

        return $result;
    }
bartko-s commented 6 years ago

Implemented. Will be released with next version (v.3.1.0)