Home > Article > Backend Development > How to convert php array to json
How to convert a php array into json: first create a PHP sample file; then define an array; finally, use the "json_encode($arr);" method to convert the array into json format data.
The operating environment of this tutorial: Windows 7 system, PHP version 5.6. This method is suitable for all brands of computers.
Recommended: "PHP Video Tutorial"
How to convert php array into json:
Convert PHP Convert the 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}
Function | Description |
---|---|
json_encode | JSON encoding for variables |
json_decode | JSON format Decode the string and convert it into a PHP variable |
json_last_error | Return the last error that occurred |
PHP json_encode()
is used to JSON encode variables. This function returns JSON data if executed successfully, otherwise it returns FALSE.
string json_encode ( $value [, $options = 0 ] )
The following example demonstrates Learn how to convert PHP objects into JSON format data:
<?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); ?>
The execution result of the above code is:
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
PHP json_decode() function is used to decode characters in JSON format The string is decoded and converted into a PHP variable.
mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
json_string: The JSON string to be decoded 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.
The following example demonstrates how to decode JSON data:
The execution result of the above code is:
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) }
This method is applicable to all brands of computers.
The above is the detailed content of How to convert php array to json. For more information, please follow other related articles on the PHP Chinese website!