简体   繁体   中英

How to correctly format JSON using PHP

i'm attempting to create a RESTful API using PHP. I'm unable to format it in a way I'm used to seeing. Would appreciate some guidance. Thank.

This is the current JSON output:

 [
    {
        "boardID": "12345",
        "MQ9": "673627",
        "MQ131": "87565",
        "MQ135": "67887",
        "longitude": "51.504425",
        "latitude": "-0.1291608",
        "time": "13:32",
        "date": "2018-03-14"
    },

This is what i'm trying to achieve:

{
    "data": [
        {
        "boardID": "12345",
        "MQ9": "673627",
        "MQ131": "87565",
        "MQ135": "67887",
        "longitude": "51.504425",
        "latitude": "-0.1291608",
        "time": "13:32",
        "date": "2018-03-14"
   },

This is my PHP:

<?php
  require 'connect.php';

  if(!$con){ 
  die('Could not connect: '.mysqli_error()); 
  } 

  $result = mysqli_query($con, "SELECT * FROM airQual"); 

  while($row = mysqli_fetch_assoc($result)
  { 
  $output[]=$row; 
  } 

  echo(json_encode($output, JSON_PRETTY_PRINT)); 

  mysqli_close($con);

  ?>

You can do this one of a couple of ways, but the easy way would be to do this, adding your output to another array:

$data = array('data' => $output);
echo(json_encode($data, JSON_PRETTY_PRINT)); 

For example:

$output = array('foo'=>1,'bar'=>2,'glorp'=>3);
$data = array("data" => $output);
echo(json_encode($data, JSON_PRETTY_PRINT)); 

returns

{
    "data": {
        "foo": 1,
        "bar": 2,
        "glorp": 3
    }
}

You can also add your output to another array, as others have suggested, this way:

$output['data'] = array('foo'=>1,'bar'=>2,'glorp'=>3);
echo(json_encode($output, JSON_PRETTY_PRINT)); 

Which will give you the same return as above.

NOTE

You have a typo in your code:

while($row = mysqli_fetch_assoc($result) // missing closing )

mysqli_error() requires the connection:

 die('Could not connect: '.mysqli_error($con)); 

Try this:

<?php
  require 'connect.php';

  if(!$con){ 
  die('Could not connect'); 
  } 

  $result = mysqli_query($con, "SELECT * FROM airQual"); 

  while($row = mysqli_fetch_assoc($result))
  { 
  $output['data'][]=$row; 
  } 

  echo(json_encode($output, JSON_PRETTY_PRINT)); 

  mysqli_close($con);

  ?>

The output is correct, as you're creating an array. If you want an object, create an object!

Do something like;

$myOuput = new stdClass;
$myOuput->data = $output;
json_encode($myOutput);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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