Depending on the complexity of the directory structure you're trying to navigate i'd recommend looking at the Standard PHP Library (SPL) specifically at DirectoryIterator and RecursiveDirectoryIterator
They're going to greatly simplify navigating very complex hierarchies. The other thing that is nice is you can always wrap them with a filter iterator to filter out only particular file types or by filename etc, and then you could also wrap that in a sorting iterator, which would be more of a custom iterator, that would allow you to reorder based on whatever criteria you wanted.
Can always mix and match based on your requirements.