Home  >  Article  >  Backend Development  >  How to convert php object array to json string array

How to convert php object array to json string array

PHPz
PHPzOriginal
2023-04-25 09:05:42366browse

In PHP programming, we often need to convert an object array into a JSON string array for data transfer or storage. In this article, I will show you how to convert an array of objects to a JSON string array using built-in functions in PHP.

First, we need to create an array containing objects. An example array can be created with the following code:

$data = [
    [
        'name' => 'Tom',
        'age' => 20,
        'address' => 'Beijing',
    ],
    [
        'name' => 'Jerry',
        'age' => 22,
        'address' => 'Shanghai',
    ],
];

At this point, the $data array contains two objects, each with a name, age and address three attributes.

Next, we can use the PHP built-in function json_encode() to convert the object array into a JSON string array. json_encode() The function can encode PHP variables into JSON format strings.

The following is a sample code to convert the $data array into a JSON string array:

$json_data = json_encode($data);

In the above code, json_encode() The function converts the $data array into a JSON string and assigns the result to the $json_data variable. Now, the data in the $json_data variable will be an array of JSON strings.

If you want an easier-to-read JSON string, you can set the second parameter of the json_encode() function to JSON_PRETTY_PRINT. This parameter will cause the json_encode() function to add indentation and formatting to the JSON string when it is generated.

Here is the sample code to convert the $data array into a JSON string array using the JSON_PRETTY_PRINT flag:

$json_data = json_encode($data, JSON_PRETTY_PRINT);

In the above code, $json_data The JSON string stored in the variable will have indentation and formatting.

In conclusion, converting an array of objects to an array of JSON strings is a very useful trick in PHP programming. Using the PHP built-in function json_encode(), we can easily convert an array containing objects into a JSON string array that can be passed and stored.

The above is the detailed content of How to convert php object array to json string array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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