phpparsing

Convert dot syntax like "this.that.other" to multi-dimensional array in PHP


Just as the title implies, I am trying to create a parser and trying to find the optimal solution to convert something from dot namespace into a multidimensional array such that

$str = 's1.t1.column.1 = size:33%';

could be converted to

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

Solution

  • Try this number...

    function assignArrayByPath(&$arr, $path, $value, $separator='.') {
        $keys = explode($separator, $path);
    
        foreach ($keys as $key) {
            $arr = &$arr[$key];
        }
    
        $arr = $value;
    }
    

    CodePad

    It will loop through the keys (delimited with . by default) to get to the final property, and then do assignment on the value.

    If some of the keys aren't present, they're created.