Quick'n'dirty approach (see the "Spoiler" block below for implementation):
Add an additional variable $recursionDepth to the function declaration, by default set it to 0 .
For each subsequent recursion, call your function with $recursionDepth + 1 .
Since function variables are โvisibleโ (limited) only for the corresponding function instance, you will get an indicator of the current iteration depth.
Also line 12 of your function
$this->buildTree();
I donโt think this will work - the reason is that you are not passing your variables to the next buildTree instance.
It should probably look like this:
$this->buildTree($row[$children_field], $display_field, $children_field, $class, $id)
Here are the changes that I will make to your code to achieve what you want:
function buildTree($tree_array, $display_field, $children_field, $class='', $id='', $recursionDepth = 0, $maxDepth = false) { if ($maxDepth && ($recursionDepth == $maxDepth)) return; echo "<ul>\n"; foreach ($tree_array as $row) { echo "<li>\n"; echo $row[$display_field] . "\n"; if (isset($row[$children_field])) $this->buildTree($row[$children_field], $display_field, $children_field, $class, $id, $recursionDepth + 1, $maxDepth); echo "</li>\n"; } echo "</ul>\n"; }