Home >Backend Development >PHP Tutorial >How Can I Convert PHP Dot Notation Strings into Multidimensional Arrays?
Converting Dot Notation to Multidimensional Arrays in PHP
In PHP, it is possible to emulate a multidimensional array structure using dot notation like "this.that.other". However, this can become cumbersome to manage and edit. To address this, a method is sought to convert dot notation into a multidimensional array.
A suggested solution employs the following function:
function assignArrayByPath(&$arr, $path, $value, $separator='.') { $keys = explode($separator, $path); foreach ($keys as $key) { $arr = &$arr[$key]; } $arr = $value; }
This function iterates through the keys separated by dots, creating any missing keys along the way, and ultimately assigning the desired value.
For example, the following dot notation:
s1.t1.column.1 = size:33%
Can be converted to a multidimensional array like so:
assignArrayByPath($source, 's1.t1.column.1', 'size:33%'); echo $source['s1']['t1']['column']['1']; // Output: size:33%
The above is the detailed content of How Can I Convert PHP Dot Notation Strings into Multidimensional Arrays?. For more information, please follow other related articles on the PHP Chinese website!