Odyss3us
Odyss3us

Reputation: 6635

Creating JSON from a comma delimited string with PHP

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!

Upvotes: 1

Views: 5133

Answers (2)

jensgram
jensgram

Reputation: 31508

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.")

Upvotes: 0

Spudley
Spudley

Reputation: 168655

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.

Upvotes: 2

Related Questions