April 11, 2012

What is the optimal string format for converting to an array?

Question by amiawizard

I’m producing a string with GROUP_CONCAT in MySQL.

There are 2 columns I need to select for each row being id and name, how should I format the string in the query so I can produce an array that couples the ids and names in PHP at optimal speed?

For example (my attempt):
GROUP_CONCAT producing

{"id":1,"name":"python"},{"id":2,"name":"ruby"}

Then convert this to an array in PHP.

Answer by Starx

I dont know why you are attempting this. But this query should work

SELECT * FROM `yourtable` GROUP_CONCAT(
    CONCAT('{"id":"',id,'","name":"',name,'"}') 
    separator ',')

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!