I remember back when I as learning PHP I had to write a directory "spider" function to list the contents of a directory. (Including sub-directories).
The approach I took involved reading the initial contents of the base directory into an array. The plan was then to loop through the array adding any sub-directories, (and their files), recursively.