1

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!
0

The hard-coded way (untested):

function my_wrap($val) {
    return '{"test":"' . $val. '"}';
}

$parts = explode(',', 'One,Two,Three,Four,Five,Six,Seven');
$parts = array_map('my_wrap', $parts);
$json = '[' . implode(',', $parts) . ']';

(If on PHP 5.3+ you can use lambda function, cf. "Example #2.")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.