Transforming a string with an array structure like "Main.Sub.SubOfSub" into an actual array can be achieved using appropriate code. Suppose you have this string value:
Main.Sub.SubOfSub
And a corresponding data item:
SuperData
The goal is to construct an array with the following structure:
Array ( [Main] => Array ( [Sub] => Array ( [SubOfSub] => SuperData ) ) )
To perform this conversion, consider the following code snippet:
<code class="php">$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 essentially implements the logic of creating an associative array structure based on the provided string path. It iterates through the path segments, creating nested arrays as necessary and assigning the provided data to the final segment of the path.
By using the reference operator (&), the code modifies the original target array directly, ensuring that the resulting array has the desired structure.
The above is the detailed content of How Can a String with an Array Structure Be Transformed into an Actual Array?. For more information, please follow other related articles on the PHP Chinese website!