Home > database >  How to format a json response in php
How to format a json response in php

Time:05-09

I am new to php and am trying to return a json response in a particular structure. 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:

enter image description here

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:

enter image description here

And Here is how my database looks like: enter image description here How can I achieve this?

CodePudding user response:

You ask for stuff that we are unsure if db result returns but as nice_dev pointed out, you need something like this:

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