Home  >  Article  >  Backend Development  >  How to define string as array object array in php

How to define string as array object array in php

PHPz
PHPzOriginal
2023-04-18 14:08:22391browse

In PHP, when we need to define a string as an array of array objects, we can do it through the following steps.

Step 1: Convert the string into JSON format

First, we need to convert the string into JSON format. In PHP, you can use the json_encode() function to convert an array into a JSON format string, as shown below:

$array = array('name' => 'John', 'age' => 30, 'city' => 'New York');
$json = json_encode($array);

At this time, the variable $json The following JSON format string will be saved in:

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

Step 2: Decode the JSON format string into an array object array

Next, we need to convert the JSON format String decoded into an array of array objects. In PHP, you can use the json_decode() function to decode a JSON format string into an array object, as shown below:

$array = json_decode($json);

At this time, the variable $array The following array objects will be saved in:

Array
(
    [name] => John
    [age] => 30
    [city] => New York
)

If you want to decode the JSON format string into an array of array objects, you need to set the second parameter to true, as shown below:

$array = json_decode($json, true);

At this time, the following array object array will be stored in the variable $array:

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 30
            [city] => New York
        )

)

The above is how to define a string into an array of array objects. In this way, we can easily and quickly convert a string into an array of array objects for processing.

The above is the detailed content of How to define string as array object array in php. 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