Home > Backend Development > PHP Tutorial > How to Efficiently Convert Dot Syntax to Multi-Dimensional Arrays in PHP?

How to Efficiently Convert Dot Syntax to Multi-Dimensional Arrays in PHP?

DDD
Release: 2024-11-29 20:32:10
Original
784 people have browsed it

How to Efficiently Convert Dot Syntax to Multi-Dimensional Arrays in PHP?

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;
}
Copy after login

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%"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template