Question:
How can dot syntax strings, such as "this.that.other", be efficiently converted into multidimensional arrays in PHP?
Answer:
A highly effective solution is to utilize a recursive function like the one below:
function assignArrayByPath(&$arr, $path, $value, $separator='.') { $keys = explode($separator, $path); foreach ($keys as $key) { $arr = &$arr[$key]; } $arr = $value; }
This function iteratively traverses the array, using the '.' as a separator, creating any missing keys along the way, until it reaches the desired property and sets its value.
For instance, with the following sample string: "s1.t1.column.1 = size:33%", the function would generate an array structure equivalent to:
$source = []; assignArrayByPath($source, 's1.t1.column.1', 'size:33%'); print_r($source); // Outputs: ['s1' => ['t1' => ['column' => ['1' => 'size:33%']]]]
The above is the detailed content of How to Efficiently Convert Dot Syntax Strings to Multidimensional Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!