Search code examples
phparraysmultidimensional-arraystring-parsingdelimited

Parse array of strings composed of dot.separated.keys into a multidimensional array


I would like to explode an array to another array based on a key.

For example :

[
  {
    "key": "menu.company.footer",
    "content": "this is an example"
  },
  {
    "key": "menu.company.home.foo",
    "content": "bar"
  }
]

Would become:

[
  {
    "menu": 
    {
      "company": 
      {
        "footer": "this is an example"
      }
    }
  },
  {
    "menu": 
    {
      "company": 
      {
        "home": 
        {
          "foo": "bar"
        }
      }
    }
  }
]

Here is what I have done:

  1. Done a foreach through my array
  2. Explode the key
  3. Done a for with the count of the explode

How do I create the parent/children system dynamically? I don't know how many level there will be.


Solution

  • This is a frequent question with a little twist. This works:

    foreach($array as $k => $v) {
        $temp  = &$result[$k];
        $path  = explode('.', $v['key']);
    
        foreach($path as $key) {
            $temp = &$temp[$key];
        }
        $temp = $v['content'];
    }
    print_r($result);
    

    Using a reference & allows you to set the $temp variable to a deeper nested element each time and just add to $temp.

    • Loop through array and explode each key element
    • Loop through exploded values and create an array with the keys, nesting as you go
    • Finally, set the value of the multidimensional array to the content element

    Also see How to write getter/setter to access multi-level array by key names? for something that may be adaptable.