Home >Backend Development >PHP Tutorial >How to Convert Dot-Delimited Strings to Multidimensional Arrays in PHP?

How to Convert Dot-Delimited Strings to Multidimensional Arrays in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-28 11:58:10742browse

How to Convert Dot-Delimited Strings to Multidimensional Arrays in PHP?

Convert Dot Syntax to Multi-Dimensional Array in PHP

Converting dot-delimited namespace strings to multidimensional arrays can be a valuable tool for parsing and restructuring data. To achieve this, consider the following approach:

Optimal Solution:

The optimal solution involves using a recursive function that traverses the dot-delimited string and creates the corresponding array structure. Here's the code:

function assignArrayByPath(&$arr, $path, $value, $separator = '.') {
    $keys = explode($separator, $path);

    foreach ($keys as $key) {
        $arr = &$arr[$key];
    }

    $arr = $value;
}

How it Works:

  1. explode($separator, $path): This splits the dot-delimited string into an array of keys.
  2. The foreach loop iteratively traverses the keys, accessing the corresponding array elements using the &$arr reference.
  3. The assignment $arr = $value assigns the provided value to the final array element.

Example:

Using the code:

$source = [];
assignArrayByPath($source, 's1.t1.column.1', 'size:33%');

Will result in:

$source['s1']['t1']['column']['1'] = 'size:33%';

The above is the detailed content of How to Convert Dot-Delimited Strings to Multidimensional Arrays in PHP?. 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