The easiest way is to write a recursive function, that is, a function which calls itself. This is fine for small tree structures, but bad for large ones.
function recursiveFunction( $i, $limit )
{
echo $i;
++$i;
if( $i < $counter )
{
recursiveFunction( $i, $limit );
}
}
recusiveFunction( 5, 10 ); Counts from 5 to 10
Each recursive call to the function creates a stack, and if the stack gets too big PHP will eventually crash with a stack overflow.
The solution to handling big tree structures is in the way in which the data is stored, and gathered. It's a bit complex so here is an article: modified preorder tree traversal.