I just wrote a PHP library baopham/tree-parser to parse a specific tree content to PHP objects.

This library can parse this tree content:

1
2
3
4
5
6
7
8
9
10
   Root
    |- Level 1 - Order 1
      |- Level 2 - Order 2
        |- Level 3 - Order 3
        |- Level 3 - Order 4
      |- Level 2 - Order 5
    |- Level 1 - Order 6
      |- Level 2 - Order 7
        |- Level 3 - Order 8
          |- Level 4 - Order 9

into this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
foreach ($root->children as $child) {
    print $child->name;

    print $child->order;

    print $child->level;

    print_r($child->children);

    print_r($child->children[0]->children);

    print $child->children[0]->parent === $child;
}

print $root->isRoot

// assuming we got the $lastLeaf after done traversing down.
print $lastLeaf->parent->parent->parent->parent === $root

Advanced

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
$tree = <<<TREE
  Root
    |- Level 1 - Order 1
      |- Level 2 - Order 2
        |- Level 3 - Order 3
        |- Level 3 - Order 4
      |- Level 2 - Order 5
    |- Level 1 - Order 6
      |- Level 2 - Order 7
        |- Level 3 - Order 8
          |- Level 4 - Order 9
TREE;

$parser = new BaoPham\TreeParser($tree);

$parser->parse();

$structure = $parser->getStructure();

// Get nodes at level 3
$level3Nodes = $structure[3];
// Get node at level 3, order 4
$node = $structure[3][4];

// Get last leaf
$orderedNodes = $parser->getOrderedNodes();
$lastLeaf = $orderedNodes[count($orderedNodes) - 1];

Comments