Home > Article > Backend Development > 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!