Home  >  Article  >  Backend Development  >  How to Convert a Dot-Delimited String to a Nested Array?

How to Convert a Dot-Delimited String to a Nested Array?

DDD
DDDOriginal
2024-10-31 03:36:01632browse

How to Convert a Dot-Delimited String to a Nested Array?

Converting a Dot-Delimited String to a Nested Array

Given a string representing a nested array structure, such as "Main.Sub.SubOfSub", and a corresponding value like "SuperData", the goal is to transform this data into an actual nested array.

To achieve this conversion, here's a detailed solution:

$key = "Main.Sub.SubOfSub";
$target = array();
$value = "SuperData";

$path = explode('.', $key); // Split the string into an array of keys
$root = &$target; // Reference to the main array

while (count($path) > 1) { // Iterate through the path array
    $branch = array_shift($path); // Get the current branch
    if (!isset($root[$branch])) {
        $root[$branch] = array(); // Create the branch if it doesn't exist
    }
    $root = &$root[$branch]; // Update the reference to the current branch
}

$root[$path[0]] = $value; // Set the value at the end of the path

This code effectively creates a nested array based on the path specified in the string. The variable $root serves as a reference to the current nested level within the array, ensuring that values are assigned to the correct branch as we traverse the path.

The above is the detailed content of How to Convert a Dot-Delimited String to a Nested 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