The
In PHP we can convert arrays into JSON format. Both indexed and associative arrays can be converted. This conversion is done using the json_encode()
method in PHP, which converts a value into a JSON object.
json_encode($value, options,depth)
$value
: This represents the value/variable to be encoded.options
: The flags
or options
parameter is to specify options that you wish to apply to the method.depth
: Depth has a maximum value of 512 and must be greater than zero.This method returns the JSON object of the value parsed.
In the code below, the array variables $indexArray
and $assocArray
will be converted into JSON objects.
<?php//An index array$indexArray = array("Volvo", "BMW", "Toyota");//associative array$assocArray = array("Peter"=>35, "Ben"=>37, "Joe"=>43);// A string value$aStringVal = "I am encoding this string";$a = json_encode($indexArray) ;$b = json_encode($assocArray) ;$c = json_encode($aStringVal) ;echo $a . "\n";echo $b . "\n";echo $c . "\n";?>