I have a multi-dimensional array in PHP. I do not have control over the content of this array. However, the structure should be something along the lines of the following example:
$x = array (
'id-1' => array (
'title' => 'First',
'children' => array (
'id-2' => array (
'title' => 'Second',
'children' => array(),
),
'id-3' => Array (
'title' => 'Third',
'children' => array (
'id-4' => array (
'title' => 'Fourth',
'children' => array(),
),
'id-5' => array (
'title' => 'Fifth',
'children' => array(),
),
),
),
),
),
'id-6' => array (
'title' => 'Sixth',
'children' => array (),
),
'id-7' => array (
'title' => 'Seventh',
'children' => array (),
),
);
Please note this is only an example, the array could be different every time, but the same structure holds, in other words, it could go as many levels as deep as it could, and it could have as many items of the same structure as above.
I am also passed a second array, something like this
$y = array('id-1','id-3','id-4');
Given the information above, I should be able to do something like this
$x['id-1']['children']['id-3']['children']['id-4']['children'] = $new_child // Where $new_child will be a new sub array added
How can I generate the last bit of code? In other words, how can I convert the path described in $y
into the actual reference to add $new_child
I am thinking it should be a foreach
or a for
loop, but I am not sure how to do it. I hit a wall. The solution should be generic that it should work on any input that is passed through $y.
Please note that it is always assumed the content of $y is correct. In other words, the path described in $y always exists.
Any help would be appreciated. Thanks.