Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?
- $tree = <<<QQ
- Gardening Tools
- Pruners & Loppers
- Loppers
- Pruners
- Shovels & Cultivators
- Cultivators & Tillers
- Manual Weeders
- Shovels
- Trowels & Spades
- Size 1
- Size 2
- More tools
- Even more tools
- Other Things
- More things
- Gardening & Horticulture Books
- Flower Books
- Annuals
- Perennials
- QQ;
- $tree_struct = tree( $tree );
- //var_dump( $tree_struct );
- print_tree( $tree_struct );
- function tree( $arg_tree ) {
- $twig = Array();
- $twig[0] = Array( 'value' => "ROOT", 'children' => Array() );
- foreach( preg_split( '/\n/', $arg_tree ) as $line ){
- $lead_regex = '/^' . str_repeat( '\s{4}', count( $twig ) - 1 ) . '/';
- while ( !preg_match( $lead_regex, $line ) ){
- array_pop($twig);
- $lead_regex = '/^' . str_repeat( '\s{4}', count( $twig ) - 1 ) . '/';
- }
- array_push($twig[count($twig)-1]['children'], Array( 'value' => preg_replace( '/^\s*/', '', $line ), 'children' => Array() ));
- #reference to the last element we created, pushed onto working twig
- array_push($twig, &$twig[count($twig)-1]['children'][count($twig[count($twig)-1]['children'])-1]);
- }
- return $twig[0];
- }
- function print_tree($arg_tree, $arg_depth=0) {
- print $arg_depth . str_repeat( ' ',$arg_depth) . $arg_tree['value'] . "\n";
- foreach( $arg_tree['children'] as $child ) {
- print_tree($child,$arg_depth+1);
- }
- }
- ?>
Add Comment
Please, Sign In to add comment