dpj0015
2018-08-14 16:45
浏览 33
已采纳

使用php从MySql编写JSON文件

I want to add Data before the array and it is written into the converted json. I have checked that there are no errors when converting, but why isn't there?

This the code

$response = array();
while($row =mysqli_fetch_assoc($result))
{
    $response[] = $row;
}
echo json_encode($response);
    //write to json file
$fp = fopen('op.json', 'w');
fwrite($fp, json_encode('{"Data":', $response), '}');// JSON_PRETTY_PRINT
fclose($fp);

Previous results like this

[
  {
    "id": "6",
    "name": "kiko",
    "score": "999"
  },
  {
    "id": "9",
    "name": "johyn",
    "score": "88"
  },
  {
    "id": "12",
    "name": "aaaani",
    "score": "99"
  }
]

I want the results like this

{
  "Data": [
    {
      "id": "6",
      "name": "kiko",
      "score": "999"
    },
    {
      "id": "9",
      "name": "johyn",
      "score": "88"
    },
    {
      "id": "12",
      "name": "aaaani",
      "score": "99"
    }
  ]
}

图片转代码服务由CSDN问答提供 功能建议

我想在数组之前添加 数据 写入已转换的json。 我已经检查过转换时没有错误,但为什么不存在?

这个代码

  $ response = array(); 
while($ row = mysqli_fetch_assoc($ result))
 {
 $ response [] = $ row; 
} 
echo json_encode($ response); 
 /  /写入json文件
 $ fp = fopen('op.json','w'); 
 nfwrite($ fp,json_encode('{“Data”:',$ response),'}'); //  JSON_PRETTY_PRINT 
fclose($ fp); 
   
 
 

以前的结果

  [
 {
 n  id“:”6“,
”名称“:”kiko“,
”得分“:”999“
},
 {
”id“:”9“,
”name“:”  johyn“,
”得分“:”88“
},
 {
”id“:”12“,
”名称“:”aaaani“,
”得分“:”99“
  } 
] 
   
 
 

我想要这样的结果

  {
“Data”:[\  n {
“id”:“6”,
“name”:“kiko”,
“得分”:“999”
},
 {
“id”  :“9”,
“名称”:“johyn”,
“得分”:“88”
},
 {
“id”:“12”,
“名称”:“aaaani”  ,
“得分”:“99”
} 
] 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drvonr6573 2018-08-14 16:48
    已采纳

    Rather than trying to code the JSON and then json_encode() it you can use an array to generate the desired output:

    $response = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $response[] = $row;
    }
    echo json_encode($response);
        //write to json file
    $fp = fopen('op.json', 'w');
    fwrite($fp, json_encode(array('Data' => $response), JSON_PRETTY_PRINT)); // JSON_PRETTY_PRINT
    fclose($fp);
    

    In addition, json_encode() has the ability to pretty print the json by supplying the second parameter.

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题