Home > Backend Development > PHP Tutorial > How to Efficiently Convert Dot Syntax Strings to Multidimensional Arrays in PHP?

How to Efficiently Convert Dot Syntax Strings to Multidimensional Arrays in PHP?

Mary-Kate Olsen
Release: 2024-12-01 16:01:11
Original
418 people have browsed it

How to Efficiently Convert Dot Syntax Strings to Multidimensional Arrays in PHP?

Converting Dot Syntax Strings to Multidimensional Arrays in PHP

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template