Home > Backend Development > PHP Tutorial > How to Convert a Dot-Separated String into a Nested Array in PHP?

How to Convert a Dot-Separated String into a Nested Array in PHP?

Mary-Kate Olsen
Release: 2024-10-31 03:03:30
Original
966 people have browsed it

How to Convert a Dot-Separated String into a Nested Array in PHP?

Transforming a String with Array Structure into an Array

This question presents a challenge: converting a string with an array structure into an actual array. The given string follows a dot-separated structure, representing nested arrays. To transform this string, we can utilize PHP's built-in functions and logical reasoning.

First, break down the string into an array of keys using explode(). Then, iterate through these keys and construct the desired array structure. If a key doesn't exist in the current level of the array, create it.

Example code:

<code class="php">$string = "Main.Sub.SubOfSub";
$data = "SuperData";
$array = [];
$path = explode('.', $string);

$root = &$array;
while (count($path) > 1) {
    $key = array_shift($path);
    if (!isset($root[$key])) $root[$key] = [];
    $root = &$root[$key];
}
$root[$path[0]] = $data;</code>
Copy after login

This code efficiently constructs the desired array structure from the provided string, allowing you to access nested values in a structured way.

The above is the detailed content of How to Convert a Dot-Separated String into a Nested Array 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template