There are lots of suggestions in the comments that are better than my original solution. Also, with 5 years of hindsight, I’d approach it differently anyway! The way I’d do this now would be as follows:
So much simpler! PHP4 has almost disappeared so there’s no reason not to use json_encode. I’d recommend that you stop reading now and just go with that.