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:
foreach
through my arrayHow do I create the parent/children system dynamically? I don't know how many level there will be.
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
.
key
elementcontent
elementAlso see How to write getter/setter to access multi-level array by key names? for something that may be adaptable.