繁体   English   中英

如何在 php 中格式化 json 响应

[英]How to format a json response in php

我是 php 的新手,正在尝试以特定结构返回 json 响应。 到目前为止,这是我尝试过的:

 $response = array(); if ($con) { $sql = "select * from admission_view"; $result = mysqli_query($con, $sql); if ($result) { $x = 0; while ($row = mysqli_fetch_assoc($result)) { $response[$x]['id'] = $row['id']; $response[$x]['name'] = $row['name']; $response[$x]['isActive'] = $row['isActive']; $response[$x]['branchId'] = $row['branchId']; $response[$x]['branch'] = $row['branch']; $response[$x]['customerGroupId'] = $row['customerGroupId']; $response[$x]['customerGroup'] = $row['customerGroup']; $response[$x]['orderNo'] = $row['orderNo']; $x++; } echo json_encode($response, JSON_PRETTY_PRINT); } } else { echo "Connection error"; }

上面的代码返回此响应:

在此处输入图像描述

但是,我不想将“branchId”和“branch”作为单独的属性返回,而是想将它们的值传递到 branchObject 中,这样 branch.id == “branchId” 和 branch.name == “branch”。我的意思是,我如何返回以下结构中的响应:

在此处输入图像描述

这是我的数据库的样子: 在此处输入图像描述 我怎样才能做到这一点?

您要求我们不确定 db 结果是否返回的东西,但正如 nice_dev 指出的那样,您需要这样的东西:

$response = [];

if ($con) {
  $sql = "select * from admission_view";
  $result = mysqli_query($con, $sql);
  if ($result) {
    $x = 0;
    while ($row = mysqli_fetch_assoc($result)) {
      $response[$x]['id'] = $row['id'];
      $response[$x]['name'] = $row['name'];
      $response[$x]['isActive'] = $row['isActive'];
      $response[$x]['branch']['id'] = $row['branchId'];
      $response[$x]['branch']['name'] = $row['branch'];
      $response[$x]['customerGroup']['id'] = $row['customerGroupId'];
      $response[$x]['customerGroup']['name'] = $row['customerGroup'];
      $response[$x]['customerGroup']['orderNo'] = $row['orderNo'];
      $x++;
    }
    echo json_encode($response, JSON_PRETTY_PRINT);
  }
} else {
  echo "Connection error";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM