I have a multidimensional array that may or may not contain the key name one or more times. What I'd like to do is for every instance of said element insert another element, next to that element, with the key key.
So, given this array:
[
[
'noname' => 'No name',
'label' => 'I have no name'
],
[
'name' => 'foo',
'label' => 'Foo',
'fields' => [
[
'name' => 'bar',
'label' => 'Bar'
]
]
],
[
'name' => 'baz',
'label' => 'Baz'
]
]
I'd like the following output:
[
[
'noname' => 'No name',
'label' => 'I have no name'
],
[
'name' => 'foo',
'key' => 'foo-key', # This is inserted by the function
'label' => 'Foo',
'fields' => [
[
'name' => 'bar',
'key' => 'bar-key', # This is inserted by the function
'label' => 'Bar'
]
]
],
[
'name' => 'baz',
'key' => 'baz-key', # This is inserted by the function
'label' => 'Baz'
]
]
I've looked into array_walk_recursive but can't get it to work. Do I need to write my own recursive function or is there something appropriate built in that I can use for this?
array_walk_recursivecallback... I'm pretty sure I could write a custom function for this, but was still hoping for some suggestions on built in functions or other ideas I may have overlooked.