How Can a String with an Array Structure Be Transformed into an Actual Array?

Susan Sarandon
Release: 2024-10-30 05:32:28
Original
816 people have browsed it

How Can a String with an Array Structure Be Transformed into an Actual Array?

Converting a String with Array Structure to an Array

Transforming a string with an array structure like "Main.Sub.SubOfSub" into an actual array can be achieved using appropriate code. Suppose you have this string value:

Main.Sub.SubOfSub
Copy after login

And a corresponding data item:

SuperData
Copy after login

The goal is to construct an array with the following structure:

Array
(
[Main] => Array
    (
        [Sub] => Array
            (
                [SubOfSub] => SuperData
            )

    )
)
Copy after login

To perform this conversion, consider the following code snippet:

<code class="php">$path = explode('.', $key);
$root = &amp;$target;

while (count($path) > 1) {
    $branch = array_shift($path);
    if (!isset($root[$branch])) {
        $root[$branch] = array();
    }

    $root = &amp;$root[$branch];
}

$root[$path[0]] = $value;</code>
Copy after login

This code essentially implements the logic of creating an associative array structure based on the provided string path. It iterates through the path segments, creating nested arrays as necessary and assigning the provided data to the final segment of the path.

By using the reference operator (&), the code modifies the original target array directly, ensuring that the resulting array has the desired structure.

The above is the detailed content of How Can a String with an Array Structure Be Transformed into an Actual Array?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!