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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)