A generalized solution might benefit from using a templating system, such as the ubiquitous Template::Toolkit, to actually do the grunt-work of generating the output HTML once you have “flipped” the data structure.
Or, perhaps you don’t have to actually flip the thing, because a template can grab data from a function just as easily as it can get it from a variable. So you could write a tiny function f(x,y) that returned element (y,x) ...
A template can be trivially changed, as often as (the customer | your boss | the marketing department) wants to change it. The “magic” comes from the (already in place ...) HTML parser and, maybe, just a handful of clever functions that a template can call. The issue that is most likely to be (constantly) changed, namely, “tweaking the output,” has been factored-out such that it contributes little or nothing to code complexity and ongoing maintenance.