In PHP, you can use the json_encode() function to convert an array into json format data. The syntax is "json_encode (array variable)". The json_encode() function can JSON encode variables, returning JSON data if successful, and FALSE if failed.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
json_encode() can be used in PHP Function to convert array to json format data.
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?>
The execution result of the above code is:
{"a":1,"b":2,"c":3,"d":4,"e":5}
JSON function
Function | Description |
---|---|
JSON encode the variable | |
Decode the JSON format string and convert it into a PHP variable | |
Return the last error that occurred |
json_encode
PHP json_encode() is used to JSON encode variables. This function returns JSON data if executed successfully, otherwise it returns FALSE.Syntax
string json_encode ( $value [, $options = 0 ] )
Parameters
<?php class Emp { public $name = ""; public $hobbies = ""; public $birthdate = ""; } $e = new Emp(); $e->name = "sachin"; $e->hobbies = "sports"; $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03")); echo json_encode($e); ?>
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
PHP Video Tutorial"]
json_decode
PHP json_decode() function is used to decode JSON format strings and convert them into PHP variables.Syntax
mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Parameters
json_string: To be decoded JSON string, must be UTF-8 encoded data
assoc: When this parameter is TRUE, an array will be returned, and when FALSE, an object will be returned.
depth: A parameter of type integer that specifies the recursion depth
options: Binary Mask, currently only JSON_BIGINT_AS_STRING is supported.
Example
The following example demonstrates how to decode JSON data:
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) }
Programming Video! !
The above is the detailed content of How to convert array to json format in php. For more information, please follow other related articles on the PHP Chinese website!