Home >Backend Development >PHP Tutorial >How to Convert Dot-Delimited Strings to Multidimensional Arrays in PHP?
Convert Dot Syntax to Multi-Dimensional Array in PHP
Converting dot-delimited namespace strings to multidimensional arrays can be a valuable tool for parsing and restructuring data. To achieve this, consider the following approach:
Optimal Solution:
The optimal solution involves using a recursive function that traverses the dot-delimited string and creates the corresponding array structure. Here's the code:
function assignArrayByPath(&$arr, $path, $value, $separator = '.') { $keys = explode($separator, $path); foreach ($keys as $key) { $arr = &$arr[$key]; } $arr = $value; }
How it Works:
Example:
Using the code:
$source = []; assignArrayByPath($source, 's1.t1.column.1', 'size:33%');
Will result in:
$source['s1']['t1']['column']['1'] = 'size:33%';
The above is the detailed content of How to Convert Dot-Delimited Strings to Multidimensional Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!