Home >Backend Development >PHP Tutorial >How Can I Recursively Convert Dot Syntax Strings to Multidimensional Arrays in PHP?
How to Create a Multidimensional Array from Dot Syntax in PHP
In PHP, converting dot syntax (like "this.that.other") into a multidimensional array can be a useful task for organizing data. Here's how to accomplish this conversion:
Using a Recursive Function:
The following function, assignArrayByPath(), can recursively navigate the dot syntax and create a multidimensional array:
function assignArrayByPath(&$arr, $path, $value, $separator='.') { $keys = explode($separator, $path); foreach ($keys as $key) { $arr = &$arr[$key]; } $arr = $value; }
How it works:
The function takes four parameters:
Example:
To convert the dot syntax "s1.t1.column.1" to a multidimensional array, use the following code:
$source = []; assignArrayByPath($source, 's1.t1.column.1', 'size:33%'); echo $source['s1']['t1']['column']['1']; // Outputs: 'size:33%'
This approach provides a flexible and recursive method for converting complex dot syntax into multidimensional arrays in PHP, ensuring that even non-existent keys are automatically created. It can be particularly useful for parsing nested data structures into a structured array format.
The above is the detailed content of How Can I Recursively Convert Dot Syntax Strings to Multidimensional Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!