I think writing this all within a call to appendPQExpBuffer() is excessive. You can make an array or structure to search through and then append the result to the buffer.
Hmm, like a custom struct we loop through? I will look into implementing that and submit a new patch.