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.

5
  • 1
    Do you mean user.data.4 instead of users.data.4? Commented Mar 29, 2018 at 19:46
  • 1
    @Alejandro I edited assuming users.data.4 was a typo. If I was mistaken, you can re-edit, but if you do please also explain why that should generate the expected output. Commented Mar 29, 2018 at 19:53
  • Related: stackoverflow.com/q/37590590/2943403 Commented Jul 3, 2022 at 16:09
  • Proof of dupe appropriateness: 3v4l.org/HJeLh Commented Jul 3, 2022 at 16:16
  • Also Related: stackoverflow.com/a/9636021/2943403 Commented Jul 4, 2022 at 9:00

1 Answer 1

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
        )

)
Sign up to request clarification or add additional context in comments.

5 Comments

FYI... Works great without if (!isset($ref[$part])) $ref[$part]=[];
Oh, yes. Right @AbraCadaver. Thank you! But. humm... Why $ref = &$ref[$part] don't throw an "undefined index"?
@AbraCadaver Ok. That because of the reference. We can create a reference to an undefined value (3v4l.org/8pTaK).
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. php.net/manual/en/language.references.whatdo.php
@AlejandroGuevara You need something like this 3v4l.org/TI3Wd ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.