I have a function that's doing this correctly, but I feel as though this can be done (possibly) with minimal code, with recursion, but I'm just wracking my brain. Basically I have JSON that gets decoded to an array. What I want to do is turn this:
{ "parentView": { "childViews": [ { "type": "container-fluid", "childViews": [ { "type": "row", "childViews": [ { "type": "slider" }, { "type": "slider" } ] } ] } ] } }
Into this:
{ "parentView": { "childViews": [ { "type": "controller", "childViews": [ { "type": "container-fluid", "childViews": [ { "type": "controller", "childViews": [ { "type": "row", "childViews": [ { "type": "controller", "childViews": [ { "type": "slider" } ] }, { "type": "controller", "childViews": [ { "type": "slider" } ] } ] } ] } ] } ] } ] } }
Here is the code I am using to make it work how I need. I am just looking for a cleaner method:
function createControls($parentView)
{
$newArr = $parentView;
foreach ($parentView as $k => $v) {
$newArr[$k] = [
'type' => 'control',
'childViews' => $v
];
if ($v['childViews']) {
foreach ($v['childViews'] as $kk => $vv) {
$newArr[$k]['childViews']['childViews'] = [
'type' => 'control',
'childViews' => $vv
];
if ($vv['childViews']) {
foreach ($vv['childViews'] as $_k => $_v) {
$newArr[$k]['childViews']['childViews']['childViews']['childViews'][$_k] = [
'type' => 'control',
'childViews' => $_v
];
}
}
}
}
}
return $newArr;
}
$newArr = createControls($arr['parentView']['childViews']);
$arr['parentView']['childViews'] = $newArr;