简体   繁体   English

如何在 php 中格式化 json 响应

[英]How to format a json response in php

I am new to php and am trying to return a json response in a particular structure.我是 php 的新手,正在尝试以特定结构返回 json 响应。 Here is what I have tried so far:到目前为止,这是我尝试过的:

 $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"; }

The code above returns this response:上面的代码返回此响应:

在此处输入图像描述

However, instead of returning for example "branchId" and "branch" as individual properties, I want to pass their values inside a branchObject such that branch.id == "branchId" and branch.name == "branch".I mean, How may I return the response in the following structure:但是,我不想将“branchId”和“branch”作为单独的属性返回,而是想将它们的值传递到 branchObject 中,这样 branch.id == “branchId” 和 branch.name == “branch”。我的意思是,我如何返回以下结构中的响应:

在此处输入图像描述

And Here is how my database looks like:这是我的数据库的样子: 在此处输入图像描述 How can I achieve this?我怎样才能做到这一点?

You ask for stuff that we are unsure if db result returns but as nice_dev pointed out, you need something like this:您要求我们不确定 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