In web development, we often need to return data to the front end in JSON format to facilitate access by client scripts such as JavaScript. In PHP, we can use the json_encode() function to convert a PHP array into a JSON string.
The following is an example. We define a PHP array named $student, and then use the json_encode() function to convert it into a JSON string and return:
$student = array( 'name' => 'Sam', 'age' => 18, 'school' => 'ABC High School' ); $json_str = json_encode($student); echo $json_str;
Output at this time $json_str is a string in JSON format:
{ "name":"Sam", "age":18, "school":"ABC High School" }
As you can see, the JSON string represents data in the form of key-value pairs, and uses curly brackets to represent the entire data object.
When the array is more complex, we can also use the second parameter $options in the json_encode() function, which is a control option that can specify that we want to convert the PHP array into a JSON string. Way. The following are some common options for $options:
The following is an example. We define a PHP array named $class, which contains information about multiple students. We use the $options option to force the PHP array into an object, and Use the JSON_PRETTY_PRINT option to format the output:
$class = array( array('name' => 'John', 'age' => 17, 'school' => 'ABC High School'), array('name' => 'Mike', 'age' => 18, 'school' => 'DEF High School'), array('name' => 'Lucy', 'age' => 16, 'school' => 'GHI High School') ); $json_str = json_encode($class, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT); echo $json_str;
The output JSON string is as follows:
{ "0": { "name": "John", "age": 17, "school": "ABC High School" }, "1": { "name": "Mike", "age": 18, "school": "DEF High School" }, "2": { "name": "Lucy", "age": 16, "school": "GHI High School" } }
In short, converting an array into JSON format in PHP is very simple, just call the json_encode() function That’s it. At the same time, we can also control the format of the output JSON string through the $options option.
The above is the detailed content of Convert array to json format PHP. For more information, please follow other related articles on the PHP Chinese website!