convert to json php code example

Example 1: php convert array to json object

$myArr = array("apple", "banana", "mango", "jackfruit");

$toJSON = json_encode($myArr);

echo $toJSON;

Example 2: php json encode

$person = array( 
    "name" => "Johny Carson", 
    "title" => "CTO"
); 
$personJSON=json_encode($person);//returns JSON string

Example 3: php convert array to json

{} = json_encode([]);

Example 4: convert stdclass to json in php

$stdClass = new stdClass();
$stdClass->name = "avatar";
$stdClass->age = 31;
$json_data = json_encode ((array) $stdClass);
print_r($json_data); //{"name":"avatar","age":31}