Home > Backend Development > PHP Problem > How to convert string into array object in php

How to convert string into array object in php

PHPz
Release: 2023-04-24 16:54:55
Original
578 people have browsed it

When developing web applications, we often need to parse and process the string data received from the front end, and these strings may be strings separated by specific symbols. In this case, we need to convert this string into Array objects to facilitate manipulation and processing. In PHP, there are many ways to convert strings into array objects. Below we briefly introduce some commonly used methods.

Convert a string into a one-dimensional array

PHP provides a explode function to decompose a string into multiple array elements according to the specified delimiter. , the syntax format of this function is as follows:

array explode(string $separator, string $string, int $limit);
Copy after login

This function receives three parameters, where $separator is the separator, which can be a string or character, or it can be separated by multiple A string composed of characters; $string is the string that needs to be decomposed; $limit is used to limit the number of decompositions. If this parameter is not specified, the entire string will be decomposed into array elements.

Next, we use a specific example to demonstrate how to use the explode function to convert a string into a one-dimensional array. Suppose we have a string $str, which contains multiple words separated by commas. We need to decompose them into a one-dimensional array. The code is as follows:

$str = "apple, banana, orange, pear";
$arr = explode(", ", $str);

print_r($arr);
Copy after login

After executing the code , the output result is as follows:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => pear
)
Copy after login

As you can see, the explode function takes each decomposed string as an array element and puts it into an array. This way we can easily process and store this data through array operations.

Convert a string into a two-dimensional array

If we need to convert a string into a two-dimensional array, there are two common methods: one is to use explode The function is decomposed before performing array operations. The other is to use the json_decode function to convert the JSON format string into an array object. Below we will introduce these two methods respectively.

Use the explode function for array splicing

If our string data has been arranged in a specific format, and we know the name corresponding to each field, then We can use the explode function to decompose and splice to generate a two-dimensional array. Let's use a specific example to demonstrate. Suppose we have a string $str, whose format is:

apple,10
banana,20
orange,30
pear,40
Copy after login

In each data row, the first one is separated by commas The word is the name of the fruit and the second is the number of fruits. We need to convert these data into a two-dimensional array. The code is as follows:

$str = "apple,10\nbanana,20\norange,30\npear,40";
$rows = explode("\n", $str);

foreach ($rows as $row) {
    $arr = explode(",", $row);
    $data[] = ["name" => $arr[0], "count" => $arr[1]];
}

print_r($data);
Copy after login

After executing the code, the output result is as follows:

Array
(
    [0] => Array
        (
            [name] => apple
            [count] => 10
        )

    [1] => Array
        (
            [name] => banana
            [count] => 20
        )

    [2] => Array
        (
            [name] => orange
            [count] => 30
        )

    [3] => Array
        (
            [name] => pear
            [count] => 40
        )

)
Copy after login
Copy after login

As you can see, we first use explodeThe function decomposes the entire string into a row array according to newline characters, and then uses the explode function in each row of data to decompose the data into a key value array according to commas, and finally assigns each key value array Give a new two-dimensional array. This method is relatively simple and practical, but it requires us to predict the data format and the delimiter of each row of data in advance.

Use the json_decode function to convert the JSON format string

If we serialize the data into a JSON format string, and then use the json_decode function to Convert it into an array object, then we can easily process data in any format. The specific code is as follows:

$str = '[{"name":"apple","count":10},{"name":"banana","count":20},{"name":"orange","count":30},{"name":"pear","count":40}]';
$data = json_decode($str, true);
print_r($data);
Copy after login

After executing the code, the output result is as follows:

Array
(
    [0] => Array
        (
            [name] => apple
            [count] => 10
        )

    [1] => Array
        (
            [name] => banana
            [count] => 20
        )

    [2] => Array
        (
            [name] => orange
            [count] => 30
        )

    [3] => Array
        (
            [name] => pear
            [count] => 40
        )

)
Copy after login
Copy after login

As you can see, we first serialize the data into a JSON format string, and then use json_decodeThe function converts it into an array object. This method can handle data in any format, and can directly parse and process the JSON format data transmitted from the front end, which is very practical for web development.

Convert a string into an object

Sometimes we don’t need an array, but an object to directly manipulate the data. In this case, we can use the stdclass# provided in PHP. ##Standard class to create an empty object and construct a data object through attribute assignment. The specific code is as follows:

$str = '{"name":"张三","age":20,"gender":"男"}';
$obj = json_decode($str);

print_r($obj);
echo $obj->name;
Copy after login
After executing the code, the output result is as follows:

stdClass Object
(
    [name] => 张三
    [age] => 20
    [gender] => 男
)
张三
Copy after login
As you can see, we first use the

json_decode function to convert the JSON format string into a Object. In this object, the attribute name is the key value in the JSON data, and the attribute value is the corresponding value in the JSON data. We can access or modify these property values ​​through properties.

To summarize, converting a string into an array object is one of the most basic and important operations in web development. PHP provides a variety of methods to implement this process. We need to flexibly choose different methods according to actual needs. Perform operations to better process and manipulate data.

The above is the detailed content of How to convert string into array object 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