Home > Backend Development > PHP Problem > How to convert List data to JSON array in PHP

How to convert List data to JSON array in PHP

PHPz
Release: 2023-04-04 22:52:02
Original
661 people have browsed it

In PHP, converting a List to a JSON array is relatively simple. In this article, we will explore how to generate a JSON array from PHP’s List data structure.

First, we need to define a List in PHP. We can use PHP arrays instead of Lists in Java. The following is the form of an example array:

$list = array(
    array("id" => 1, "name" => "John"),
    array("id" => 2, "name" => "Mary"),
    array("id" => 3, "name" => "Tom"),
);
Copy after login

Next, we need to convert the list into a json array using PHP's built-in json_encode() function. The following is an example of the converted code:

$json = json_encode($list);
Copy after login

This will generate a json string similar to the following:

[
    {"id":1,"name":"John"},
    {"id":2,"name":"Mary"},
    {"id":3,"name":"Tom"}
]
Copy after login

In the above example, we created a JSON array containing three elements. Each element is an object containing id and name keys.

If we want to convert the List into a more complex JSON array, we can add more key-value pairs. Here is an example where we change each element to an object containing four keys:

$list = array(
    array("id" => 1, "name" => "John", "age" => 25, "gender" => "male"),
    array("id" => 2, "name" => "Mary", "age" => 30, "gender" => "female"),
    array("id" => 3, "name" => "Tom", "age" => 20, "gender" => "male"),
);

$json = json_encode($list);
Copy after login

This will produce a JSON array similar to the following:

[
    {"id":1,"name":"John","age":25,"gender":"male"},
    {"id":2,"name":"Mary","age":30,"gender":"female"},
    {"id":3,"name":"Tom","age":20,"gender":"male"}
]
Copy after login

By using PHP's json_encode function, we can easily convert List to JSON array. Whether we want to convert a simple list or a complex object to JSON, PHP provides us with a simple and effective way.

The above is the detailed content of How to convert List data to JSON array in PHP. For more information, please follow other related articles on the PHP Chinese website!

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