The following example shows how to convert an array into JSON
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

// Returns the JSON representation of a value (pretty printed)
echo json_encode($arr, JSON_PRETTY_PRINT);
Result of the above code
{
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4,
    "e": 5
}
The following example shows how the PHP objects can be converted into JSON
class Emp {
    public $name = "";
    public $hobbies  = [];
    public $birthdate = "";
}

$e = new Emp();
$e->name = "sachin";
$e->hobbies  = ["sport", "reading"];
$e->birthdate = date('Y-m-d', strtotime('2015-11-18'));

echo json_encode($e);
The above code will produce the following result
{"name":"sachin","hobbies":["sport","reading"],"birthdate":"2015-11-18"}
Decoding JSON in PHP (json_decode) The following example shows how PHP can be used to decode JSON objects
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

// Decoding into an object
var_dump(json_decode($json));

// Decoding into an array
var_dump(json_decode($json, true));
While executing, it will produce the following result
object(stdClass)#1 (5) {
  ["a"]=> int(1)
  ["b"]=> int(2)
  ["c"]=> int(3)
  ["d"]=> int(4)
  ["e"]=> int(5)
}
array(5) {
  ["a"]=> int(1)
  ["b"]=> int(2)
  ["c"]=> int(3)
  ["d"]=> int(4)
  ["e"]=> int(5)
}
by Valeri Tandilashvili
4 years ago
JSON
JSON Tutorial
1
Pro tip: use ```triple backticks around text``` to write in code fences