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

How Can I Recursively Convert Dot Syntax Strings to Multidimensional Arrays in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 05:28:17644browse

How Can I Recursively Convert Dot Syntax Strings to Multidimensional Arrays in PHP?

How to Create a Multidimensional Array from Dot Syntax in PHP

In PHP, converting dot syntax (like "this.that.other") into a multidimensional array can be a useful task for organizing data. Here's how to accomplish this conversion:

Using a Recursive Function:

The following function, assignArrayByPath(), can recursively navigate the dot syntax and create a multidimensional array:

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

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

    $arr = $value;
}

How it works:

  1. The function takes four parameters:

    • $arr: The multidimensional array to modify.
    • $path: The dot syntax path representing the desired key structure.
    • $value: The value to assign to the final key.
    • $separator: (Optional) The delimiter used in the dot syntax (defaults to .)
  2. The explode() function splits the path into individual keys.
  3. The function iterates through each key, using references to modify the appropriate elements in the array $arr.
  4. If a key does not exist, it is created and assigned to the $arr reference.
  5. Finally, the $value is assigned to the last key in the array.

Example:

To convert the dot syntax "s1.t1.column.1" to a multidimensional array, use the following code:

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

echo $source['s1']['t1']['column']['1']; // Outputs: 'size:33%'

This approach provides a flexible and recursive method for converting complex dot syntax into multidimensional arrays in PHP, ensuring that even non-existent keys are automatically created. It can be particularly useful for parsing nested data structures into a structured array format.

The above is the detailed content of How Can I Recursively Convert Dot Syntax 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