【问题标题】:How to add hard coded values into a JSON response如何将硬编码值添加到 JSON 响应中
【发布时间】:2022-01-10 01:46:56
【问题描述】:

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

      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"
        }
      }
    ]
  }

【问题讨论】:

  • 更改分配$response[$i]['gender']= ... $response[$i]['values']['gender']

标签: javascript php json


【解决方案1】:

几乎,添加“值”,然后您的项目然后将$response 添加到项目数组中,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);
...

【讨论】:

  • 这不是echo json_encode(['inputs' => $response], JSON_PRETTY_PRINT) 所做的吗?
【解决方案2】:

这边:

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

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2022-11-27
    相关资源
    最近更新 更多