javascript - 如何将硬编码值添加到 JSON 响应中

标签 javascript php json

我正在尝试使用 PHP 生成 JSON 以专门采用所需的形状。 下面是我的 PHP 代码片段:

      if($con){
    $sql="select * from people";
    $result=mysqli_query($con,$sql);
    if($result){
          header("Content-Type: JSON");
        $i=0;
        while($row = mysqli_fetch_assoc($result)){
            $response[$i]['gender']=$row['gender'];
            $response[$i]['first']=$row['first'];
            
            $i++;
        }
        echo json_encode($response, JSON_PRETTY_PRINT);
    }
}

这是我当前的 JSON 响应

  [
   {
      "gender":"male",
      "first":"Angela"
   },
   {
      "gender":"female",
      "first":"Krista"
   }
]

这是我想要的回应:

{
    "inputs": [
      {

        "values": {
          "gender": "male",
          "first": "Angela"
        }
      },
      {
        "values": {
          "gender": "female",
          "first": "Krista"
        }
      }
    ]
  }

最佳答案

差不多了,添加'values',然后你的items将$response添加到items数组中,json的内容类型也是application/json,你应该将$response预定义为数组,否则,如果查询为空,则在 json_encode 中使用它时,您会收到未定义的警告和空值。

...
        header("Content-Type: application/json");
        $response = [];
        while($row = mysqli_fetch_assoc($result)){
            $response[]['values'] = [
                'gender' => $row['gender'],
                'first' => $row['first']
            ];
        }
        echo json_encode(['inputs' => $response], JSON_PRETTY_PRINT);
...

关于javascript - 如何将硬编码值添加到 JSON 响应中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70646992/

相关文章:

javascript - 使用客户端代码创建文本文件

javascript - jQuery 在另一个 HTML 元素中生成 HTML 元素

javascript - 循环对象,重复仅显示一次

javascript - p :dialog not showing in tabs on tabview

javascript - 使用从内容加载的 SVG 样式表

javascript - 在 jquery 弹出窗口中禁用背景

javascript - 附加到 URL 并刷新页面

php - 如何在 Laravel 的 Eloquent ORM 中按数据透视表数据排序

php - 学说 2 : ManyToOne cascade remove causes the referenced entity to be deleted

php - 由于解码不当,Wordpress 搜索在特殊字符上失败