|  | Posted by Henk verhoeven on 03/23/07 23:30 
Hi,
 Nice, i will soon need to make a user interface component that outputs
 such a representation, so if i can help you now i can reuse the
 algorithm myself later :-) .
 
 For a start you could replace
 for ( $i = 0; $i <= $level; $i++ ) {
 echo " - ";
 }
 echo "$value\n";
 by
 for ( $i = 0; $i < $level; $i++ ) {
 echo "|   ";
 }
 echo "|-- $value\n";
 
 This would still leave two problems. I will start with the easy one:
 - the last leave is shown like |--, it should be like `--
 To solve this you only have to check for $key to be the last one:
 if ($key == count($array)-1) {
 (...)
 
 Once you have solved this it should output something like:
 |-- index.php
 |   |-- menu.php
 |   |-- content.php
 |   |-- admin_page.php
 |   |   |-- admin_function1.php.inc
 |   |   |-- admin_function2.php.inc
 |   |   |-- admin_function3.php.inc
 |   |   `-- admin_subpage.php
 |   |   |   |-- admin_subfunction1.php.inc
 |   |   |   |-- admin_subfunction1.php.inc
 
 As you see the last two lines include | below the `, it shoulr have been
 a space there. One could say that the last branche does not take into
 acount that the branche on the previous level has already ended. But how
 could it know? This info is not passed when the show_array function was
 called recursively. You need to pass this info about all the previous
 levels. That would, at the moment the recursive call is made, be an
 array holding a boolean for each level, and an empty array for the
 initial show_array call. Let's call this array $track. It can be built
 by adding the last boolean at the array that was passed through the
 parameter just before it get passed in the recursive call.
 The length of $track already tells the $level, so you can replace the
 $level parameter with this array and use count($track) where you need
 the $level.
 Oncy you have the array, you can replace
 for ( $i = 0; $i <= $level; $i++ ) {
 echo "|   ";
 by:
 forEach($track as $i => $continued) {
 echo $continued ? "|   " : "    ";
 
 I guess you can fill in the missing pieces and get it to work. I did not
 really code it out and test it so there may be something i have not noticed.
 
 Thank you for helping me with my component ;-).
 
 
 Henk Verhoeven,
 www.phpPeanuts.org.
  Navigation: [Reply to this message] |