daily pastebin goal
91%
SHARE
TWEET

Untitled

a guest May 17th, 2018 95 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?
  2.  
  3. $tree = <<<QQ
  4. Gardening Tools
  5.     Pruners & Loppers
  6.         Loppers
  7.         Pruners
  8.     Shovels & Cultivators
  9.         Cultivators & Tillers
  10.         Manual Weeders
  11.         Shovels
  12.         Trowels & Spades
  13.             Size 1
  14.             Size 2
  15.     More tools
  16.     Even more tools
  17. Other Things
  18. More things
  19. Gardening & Horticulture Books
  20.     Flower Books
  21.         Annuals
  22.         Perennials
  23. QQ;
  24.  
  25. $tree_struct = tree( $tree );
  26. //var_dump( $tree_struct );
  27.  
  28. print_tree( $tree_struct );
  29.  
  30. function tree( $arg_tree ) {
  31.  
  32.     $twig = Array();
  33.     $twig[0] = Array( 'value' => "ROOT", 'children' => Array() );
  34.  
  35.     foreach( preg_split( '/\n/', $arg_tree ) as $line ){
  36.         $lead_regex = '/^' . str_repeat( '\s{4}', count( $twig ) - 1 ) . '/';
  37.  
  38.         while ( !preg_match( $lead_regex, $line ) ){
  39.             array_pop($twig);
  40.             $lead_regex = '/^' . str_repeat( '\s{4}', count( $twig ) - 1 ) . '/';
  41.         }
  42.  
  43.         array_push($twig[count($twig)-1]['children'], Array( 'value' => preg_replace( '/^\s*/', '', $line ), 'children' => Array() ));
  44.  
  45.         #reference to the last element we created, pushed onto working twig
  46.         array_push($twig, &$twig[count($twig)-1]['children'][count($twig[count($twig)-1]['children'])-1]);
  47.     }
  48.  
  49.     return $twig[0];
  50. }
  51.  
  52. function print_tree($arg_tree, $arg_depth=0) {
  53.     print $arg_depth . str_repeat( '   ',$arg_depth) . $arg_tree['value'] . "\n";
  54.     foreach( $arg_tree['children'] as $child ) {
  55.         print_tree($child,$arg_depth+1);
  56.     }
  57. }
  58. ?>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top