Why is only the first operation run in my loop – except for on the last repeat? [closed]

Looks like you missed the { for foreach

Change this line:

foreach ( $top_level_elements as $e )

to

foreach ( $top_level_elements as $e ) {

And don’t forget to complete the curly bracket after the end of loop.