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>
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!