dongsi7759 2016-03-23 01:28 采纳率: 100%
浏览 58
已采纳

如何使用PHP向json输出添加自定义前缀

I want to add some string before the data derived from mySQL. And output them in JSON. I can fetch out the data from mySQL right for my needs. But I cannot add the prefix string to the right format.

The expected json format

{
    "message": "",//i can do this
    "value": [//but I can't do this the "value":[
        {
            "excName": "Mark",
            "excSup": "chunyun",
            "excId": 20001
        }, {
            "excName": "orion-01",
            "excSup": "orion-01",
            "excId": 20000
        }
     ]
}

PHP

while ($rec_qXcur=mysqli_fetch_assoc($sql_qXcur)){
    $data[] = array(
   "excId"=>$rec_qXcur['exc_id'],
   "excTitle"=>$rec_qXcur['exc_name'],
   "excSup"=>$rec_qXcur['exc_sup']
   );
}
//return json data
echo json_encode($data);

From PHP I got this :

{
"message":"",
//"value":[//this is missing
"0":{//not need
   "excId":"234",
   "excTitle":"Simon Cabaret - Regular Seat ",
   "excSup":"simon"
},
"1":{//not need
   "excId":"245",
   "excTitle":"Simon Cabaret - VIP Seat (01Nov15 - 30Apr16)",
   "excSup":"simon"
}

According to the expected json format. I missed "value":[. I tried adding it to the $data but it's not working.

  • 写回答

1条回答 默认 最新

  • douhui8163 2016-03-23 01:38
    关注

    You are just adding them to data. You need to add them to the value array.

    So json_encode() is probably creating an object literal {} because your array has both named elements and sequential elements. Once it only contains sequential elements, json_encode() should (I believe) return an array literal [];

    $data = array(
        'message' => 'Your message here',
        'value'   => array()
    );
    
    while ($rec_qXcur=mysqli_fetch_assoc($sql_qXcur)){
       $data['value'][] = array(
           "excId"=>$rec_qXcur['exc_id'],
           "excTitle"=>$rec_qXcur['exc_name'],
           "excSup"=>$rec_qXcur['exc_sup']
       );
    }
    
    echo json_encode($data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里