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"), );
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);
This will generate a json string similar to the following:
[ {"id":1,"name":"John"}, {"id":2,"name":"Mary"}, {"id":3,"name":"Tom"} ]
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);
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"} ]
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!