There are various ways to solve this kind of problem. You can create parent-child relationships between the elements or use a hierarchical 'tree' to organize the elements, then display them based on the parent-child relationship or their depth in the tree.
You could also solve it programmatically by storing the current "master" header value and checking to see when it changes as you loop through the values> When it does, you then fetch the next header value and continue.
Without knowing a little more about what your intent or goal is, it's difficult to get more specific.