PHP Array to JSON Conversion Guide

WBOY
Release: 2024-05-03 09:12:02
Original
351 people have browsed it

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 数组到 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;
Copy after login

Output:

{"name":"John","age":30,"city":"New York"}
Copy after login

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;
Copy after login

Output:

"{"name":"John","age":30,"city":"New York"}"
Copy after login

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;
?>
Copy after login

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"}]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!