How do I select the deepest child element from a multidimensional-array in order to add another element to that specific one in php (always knowing where it is added, so in case additional information from the parent is needed in order to create the new child)?
eg. having an array like this I want to be able to add another aaaa, bbbb, cccc to each: aaa, bbb, ccc? and later on aaaaa, bbbbb,… to each aaaa, bbbb… and so on (where each new element is aware of it's parent's name).
array(
"a"=> array(
"aa"=> array(
"aaa",
"bbb",
"ccc"
),
"bb"=> array(
"aaa",
"bbb",
"ccc"
),
"aa"=> array(
"aaa",
"bbb",
"ccc"
),
),
"b"=> array(
"aa"=> array(
"aaa",
"bbb",
"ccc"
),
"bb"=> array(
"aaa",
"bbb",
"ccc"
),
"aa"=> array(
"aaa",
"bbb",
"ccc"
),
),
"c"=> array(
"aa"=> array(
"aaa",
"bbb",
"ccc"
),
[…]
),
);
You might want to use array_walk_recursive
. It lets you itterate over all the leafs of a multidimensional array.
function add_children(&$item, $key)
{
//Here you can change item to something else (since we use &)
$item = array('aaaa', 'bbbb', 'cccc');
}
array_walk_recursive($array, 'add_children');
Disclaimar: I have not tested this code.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments