lokesh kumar
lokesh kumar

Reputation: 981

How to form JSON in PHP?

I want my PHP code to echo a JSON object like this:

{
  "accounting": [
    {
      "firstName": "John",
      "lastName": "Doe",
      "age": 23
    },
    {
      "firstName": "Mary",
      "lastName": "Smith",
      "age": 32
    }
  ]
}

How to do it in PHP?

Edit : I MEAN HOW TO FORM THIS TYPE OF JSON? My program is extracting these details from a table.

Something like this

<?php
  $sql = "SELECT * FROM details";
  $result = $conn->query($sql);

  while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

  ????????????????????
  }
  echo json_encode(????);
?>

Upvotes: 0

Views: 573

Answers (5)

Sagar
Sagar

Reputation: 269

<?php
$sql = "SELECT * FROM details";
$result = $conn->query($sql);
$data = array();
$accounting = array();
 while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $arr = array();
$arr["firstName"] = $row["firstName"];
$arr["lastName"] = $row["lastName"];
$arr["age"] = $row["age"];
array_push($accounting, $arr);
 }
 $data["accounting"] = $accounting
 echo json_encode($data);
?>

Upvotes: 1

Sagar
Sagar

Reputation: 269

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);

Output : {"a":1,"b":2,"c":3,"d":4,"e":5}

Upvotes: 0

SuryaTeja Mahidhara
SuryaTeja Mahidhara

Reputation: 119

Use json_encode($array), then it will display the array in json format.

Upvotes: 0

codeneuss
codeneuss

Reputation: 905

use json_encode()

The first and only required Parameter is an array(). The array can also be multidimensional

The functions returns a string.

http://php.net/manual/en/function.json-encode.php

Upvotes: 1

Grokify
Grokify

Reputation: 16334

The following PHP will result in the JSON you are looking for. Basically, create the corresponding PHP data structure using PHP arrays and associative arrays which will be converted to JSON arrays and objects.

$data = array(
  'accounting' => array(
    array(
      'firstName' => 'John',
      'lastName' => 'Doe',
      'age' => 23
    ),
    array(
      'firstName' => 'Mary',
      'lastName' => 'Smith',
      'age' => 32
    )
  )
);

$json = json_encode($data);

Upvotes: 4

Related Questions