Problem:
You have a string representing a nested array structure, and you need to convert it into an actual array. For instance, given the following string:
Main.Sub.SubOfSub
And a data value:
SuperData
You want to create an array like this:
Array ( [Main] => Array ( [Sub] => Array ( [SubOfSub] => SuperData ) ) )
Solution:
To transform the string into an array, you can use the following steps:
Here's a code snippet that demonstrates the steps:
<code class="php">$key = "Main.Sub.SubOfSub"; $target = array(); $value = "SuperData"; $path = explode('.', $key); $root = &$target; while(count($path) > 1) { $branch = array_shift($path); if (!isset($root[$branch])) { $root[$branch] = array(); } $root = &$root[$branch]; } $root[$path[0]] = $value;</code>
This code snippet will create the desired array structure, with the data value stored in the final key.
The above is the detailed content of How to Convert a String Representing a Nested Array Structure into an Array?. For more information, please follow other related articles on the PHP Chinese website!