0

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.

4
  • 1
    Json doesn't have a u prefix for strings (that's specific to python afaik), why do you need that? Commented Mar 25, 2014 at 6:44
  • RC, Spot on!!!...I need it to run it on the python script for spss conversion. Commented Mar 25, 2014 at 6:46
  • python understand standard json (see json module), no u needed. Commented Mar 25, 2014 at 6:49
  • Okie. How do I do it in php with the following data structure than?{'v2':{0:u'No',1:u'Yes'}, 'v3':{1:'Maybe',3:'Almost'}} Commented Mar 25, 2014 at 6:50

1 Answer 1

3

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

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

4 Comments

First of all, I would like to Thank you for your quick response. What I need is the key is in integers and not string. In your case the key for 0 is "0" whereas the one I need is 0.
Well done with the reverting of v2. I was just fiddling with this and realised that v2 was always output as an array and not as an object. Even if I set the indices as strings... Sometimes I so dislike PHP :-D
@Havelock, I agree 100% here, this type conversion is a pain and somehow stupid (changing value order changes behavior?!)
Okie. let me look at it and will mark it solved soon. Thank you

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.