Transforming Dot Syntax to Multi-Dimensional Arrays in PHP
Question:
How can you efficiently convert dot syntax, such as "this.that.other," into a multi-dimensional array in PHP?
Answer:
To achieve this conversion, consider implementing the following function:
function assignArrayByPath(&$arr, $path, $value, $separator='.') { $keys = explode($separator, $path); foreach ($keys as $key) { $arr = &$arr[$key]; } $arr = $value; }
Explanation:
This function accomplishes the desired conversion by iterating through the keys specified in the $path parameter, using the $separator as the delimiter. For each key, it accesses and updates the corresponding element in the $arr array. Finally, it assigns the $value to the lowest-level element in the array.
Example Usage:
To demonstrate the function's functionality, execute the following code:
$arr = []; assignArrayByPath($arr, 's1.t1.column.1', 'size:33%'); echo $arr['s1']['t1']['column']['1']; // Output: "size:33%"
By utilizing this function, you can effectively convert dot syntax into multi-dimensional arrays, simplifying the handling and retrieval of complex data structures.
The above is the detailed content of How to Efficiently Convert Dot Syntax to Multi-Dimensional Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!