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
Release: 2024-11-30 07:32:14
Original
142 people have browsed it

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

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

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

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!

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