Home >Backend Development >PHP Tutorial >PHP Array to JSON Conversion Guide
Method: Use json_encode() function Use json_serialize() Function example: Get data from MySQL database and convert to JSON: Connect to the database to execute SQL query Convert the result set to an associative array Convert the array to JSON
PHP Array to JSON Conversion Guide
JSON (JavaScript Object Notation) is a lightweight text data exchange format, widely used in web applications and APIs. It is often used as an alternative to PHP arrays because it is easier to transfer and parse.
How to convert PHP array to JSON?
PHP provides a variety of methods to convert arrays to JSON:
1. json_encode() function
json_encode ()
function is the most common way to convert a PHP array to a JSON string:
<?php $array = [ "name" => "John", "age" => 30, "city" => "New York" ]; $json = json_encode($array); echo $json;
Output:
{"name":"John","age":30,"city":"New York"}
2. json_serialize() function
json_serialize()
The function can also be used to convert a PHP array to a JSON string, but it is designed for the JSON specification:
<?php $array = [ "name" => "John", "age" => 30, "city" => "New York" ]; $json = json_serialize($array); echo $json;
Output:
"{"name":"John","age":30,"city":"New York"}"
Practical case: Convert data from MySQL database to JSON
The following is a practical example of converting data from the "users" table in the MySQL database to JSON:
<?php // 连接到数据库 $db = new mysqli("localhost", "username", "password", "database_name"); // 执行 SQL 查询 $query = "SELECT * FROM users"; $result = $db->query($query); // 将结果集转换为关联数组 $users = $result->fetch_all(MYSQLI_ASSOC); // 将数组转换为 JSON $json = json_encode($users); // 输出 JSON echo $json; ?>
Output:
[{"id":1,"name":"John","email":"john@example.com"},{"id":2,"name":"Jane","email":"jane@example.com"},{"id":3,"name":"Bob","email":"bob@example.com"}]
The above is the detailed content of PHP Array to JSON Conversion Guide. For more information, please follow other related articles on the PHP Chinese website!