Skip to content
Advertisement

String to multidimensional/recursive array in PHP

I have a problem with creating a recursive array with PHP.

I need to format this string to a multidimensional array with the dot-separated elements indicating multiple levels of array keys.

$str = "code.engine,max_int.4,user.pre.3,user.data.4";

The output for this example would be:

$str = array(
   "code" => "engine",
   "max_int" => 4,
   "user" => array(
      "pre" => 3,
      "data" => 4
   )
);

I will start with an explode function, but I don’t know how to sort it from there, or how to finish the foreach.

Advertisement

Answer

You could start to split using comma ,, then, split each item by dot ., remove the last part to get the “value”, and the rest as “path”. Finally, loop over the “path” to store the value:

$str = "code.engine,max_int.4,user.pre.3,user.data.4";

$array = [] ;
$items = explode(',',$str);
foreach ($items as $item) {
    $parts = explode('.', $item);
    $last = array_pop($parts);

    // hold a reference of to follow the path
    $ref = &$array ;
    foreach ($parts as $part) {
        // maintain the reference to current path 
        $ref = &$ref[$part];
    }
    // finally, store the value
    $ref = $last;
}
print_r($array);

Outputs:

Array
(
    [code] => engine
    [max_int] => 4
    [user] => Array
        (
            [pre] => 3
            [data] => 4
        )

)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement