nix, shell, perl, php, mysql and mac os x tips and tricks

Thursday, May 16, 2013

This perl code recurses down thru a category hierarchy and indents. You pass into it the category you want to drill into
01.# call the sub
02.&drillTree($code,1);
03.sub drillTree {
04. my ($root,$level) = @_;
05. my $tab = "";
06. for (my $i=1;$i<=$level;$i++) {
07.  $tab .= "\t";
08. }
09. my $drill_q = "SELECT category_code,category_name FROM $categories WHERE category_parent = '$root'";
10. my $sth = &db_query($drill_q);
11. my $rc = $sth->rows;
12. if ($rc>0) {
13.  $level++;
14.  while (my $ref = $sth->fetchrow_arrayref) {
15.   print "${tab}sub_code: $$ref[0] sub_name: $$ref[1]\n";
16.   &drillTree($$ref[0],$level);
17.  }
18. } else {
19.  $level--;
20. }
21.}
this one will print out the full path
01.# Launch the category drill-down sub
02.&drillTree($dbh,"100",0);
03.my @path = ();
04.$path[0] = "Products";
05.my @codes = ();
06.$codes[0] = "0";
07. 
08.sub drillTree {
09. 
10. my ($dbh,$root,$level) = @_;
11. my $tab = "";
12. for (my $i=1;$i<=$level;$i++) {
13.  $tab .= "\t";
14. }
15. my $drill_q = "SELECT category_code,category_name FROM $categories WHERE category_parent = '$root'";
16. my $sth = &db_query($dbh,$drill_q);
17. my $rc = $sth->rows;
18. if ($rc>0) {
19.  $level++;
20.  while (my $ref = $sth->fetchrow_arrayref) {
21.   $path[$level] = $$ref[1];
22.   $codes[$level] = $$ref[0];
23.   my $fullpath;
24.   my $fullcodes;
25.   for (my $i=1;$i<=$level;$i++) {
26.    $fullpath .= $path[$i];
27.    $fullcodes .= $codes[$i];
28.    if ($i<$level) {
29.     $fullpath .= "|";
30.     $fullcodes .= ";";
31.    }
32.   }
33.   $fullpath =~ s/®//g;
34.   $fullpath =~ s/é/e/g;
35.   print "level: $level ${tab}sub_code: $$ref[0] sub_name: $$ref[1] $fullpath $fullcodes\n";
36.    
37.   &drillTree($dbh,$$ref[0],$level);
38.  }
39. } else {
40.  $level--;
41. }
42.} # end drillTree sub