madi
madi

Reputation: 5662

Converting a php array to a unicode json

I need to convert a dynamic array to the following format. I am only posting a sample

{u'v2':{0:u'No',1:u'Yes'}, u'v3':{1:u'Maybe',3:u'Almost'}}

This is what I did:

$valLabels = array();
 $valLabelTemp1 = array();
 $valLabelTemp2 = array();

 $valLabelTemp1['v2'][0] = 'No';
 $valLabelTemp1['v2'][1] = 'Yes';
 $valLabels = $valLabelTemp1; 

 $valLabelTemp2['v3'][0] = 'Maybe';
 $valLabelTemp2['v3'][1] = 'Almost';
 $valLabels = $valLabelTemp2;

When I write the above in a text file:

fwrite($fh,json_encode($valLabels) . "\n");

I get the following output:

{"v2":["No","Yes"],"v3":["Maybe","Almost"]}

I dun want the above format. Plus I need to affix the 'U' to represent unicode. I am not sure how can I do to the format. Advance thanks.

Upvotes: 0

Views: 97

Answers (1)

user180100
user180100

Reputation:

You can do something like this:

<?php

$valLabels = array(
  'v2' => array('1' => 'Yes', '0' => 'No'), 
  'v3' => array('1' => 'Maybe','3' => 'Almost')
);

echo json_encode($valLabels);

output:

{"v2":{"1":"Yes","0":"No"},"v3":{"1":"Maybe","3":"Almost"}}

NB: we need to revert (this doesn't matter in the json result) the v2 data otherwise php does some kind of smart type convertion and you loose indices.

Demo

Upvotes: 3

Related Questions