Best way to build dynamic sub menus?

Check out this post. I had the same question and posted the working code at the end of the post: