1

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

My question is how create the parent/children system dynamically because I don't know how many level there will have.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
tomprouvost
  • 115
  • 7

1 Answers1

2

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.

Community
  • 1
  • 1
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87