Home >Backend Development >PHP Tutorial >How Can I Convert PHP Dot Notation Strings into Multidimensional Arrays?

How Can I Convert PHP Dot Notation Strings into Multidimensional Arrays?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 07:32:14109browse

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!

Statement:
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