1

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.

Syscall
  • 19,327
  • 10
  • 37
  • 52
Alejandro Reyes
  • 332
  • 5
  • 13

1 Answers1

7

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
        )

)
Syscall
  • 19,327
  • 10
  • 37
  • 52
  • FYI... Works great without `if (!isset($ref[$part])) $ref[$part]=[];` – AbraCadaver Mar 29 '18 at 20:05
  • Oh, yes. Right @AbraCadaver. Thank you! But. humm... Why `$ref = &$ref[$part]` don't throw an _"undefined index"_? – Syscall Mar 29 '18 at 20:09
  • @AbraCadaver Ok. That because of the reference. We can create a reference to an undefined value (https://3v4l.org/8pTaK). – Syscall Mar 29 '18 at 20:14
  • 1
    I hadn't refreshed my window and didn't see your comment that you found it :-) _Note: If you assign, pass, or return an undefined variable by reference, it will get created._ http://php.net/manual/en/language.references.whatdo.php – AbraCadaver Mar 29 '18 at 20:28
  • @AlejandroGuevara You need something like this https://3v4l.org/TI3Wd ? – Syscall Sep 25 '18 at 08:32