douchan0523 2014-03-25 06:42
浏览 83
已采纳

将php数组转换为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) . " ");

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.

  • 写回答

1条回答 默认 最新

  • dqyhj2014 2014-03-25 06:59
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条