tags:

views:

71

answers:

2

Hi guys,

I am trying to create JSON from a comma delimited string, the string look something like this:

One,Two,Three,Four,Five,Six,Seven

I need it to look something like this:

[{"test":"One"},{"test":"Two"},{"test":"Three"},{"test":"Four"},{"test":"Five"},{"test":"Six"},{"test":"Seven"}]

Here is the code I have thus far:

$string = mysql_fetch_array($test, true);
$woot = explode(',', $string['test']);

$json = json_encode($woot);
echo($json);

Thanx in advance!

A: 
jensgram
Thanx for the help!
+2  A: 

json_encode() will turn a PHP array into a JS array or object.

What this means is that your JSON output will probably look something like this:

['One','Two','Three','Four','Five','Six','Seven']

ie because your PHP array is a simple numeric-keyed array, it converts into a basic JS array.

The desired output is similar, except that each array element is in the form {'key':'value'} rather than just 'value'. This means that wach array element is an object (albeit one with a single key).

To produce this, you will need to adapt your PHP code after the explode, to loop through each array element and turn it into a nested array. Something like this:

foreach($woot as $key=>$value) {$woot[$key]=array('test'=>$value);}

...and then pass $woot to json_encode() as before.

That will produce pretty much the output you're looking for. Not sure why you'd want to encode it like that though -- are all those test objects really required? Are you passing into an existing JS program that requires this format? It looks a bit of a messy structure, so if so, there's probably some JS code that could do with tidying up!

Hope that helps.

Spudley
At the moment it is being used to populate a drop down list using jQuery, and the jQuery requires that format, I am still looking for ways to optimize the jQuery code since I am still new to jQuery, so I am sure it could do with some tidying up, but thanx alot for the help!