I'm working with building associative arrays using recursive function which involves carrying the path through each instance for pushing values to nested array of key
So we feed our function a base array containing 3 keys with empty arrays as values
$fooArray = array(2 => array(), 14 => array(), 8 => array());
$ids = array(2, 14, 8);
function test($fooArray, $ids) {
Our recursive function starts with looping those ids, checking for subids of each and then adding that array filled with values to key
$subids = array(5, 8, 9);
$subkeys = array_fill_keys($subids, array());
$fooArray[$id] = $subkeys;
On the second run of our recursive function, we loop through the newly added sub set of keys and rerun the process. The issue is I'm losing my parent path.
Now I can send our first $id through the function as a parent id and then push
$fooArray[$pid][$id] = $subkeys
But now what do I do for a third and fourth run? What I need is a way to build that path and carry it through each function
$path = $fooArray[$pid][$id];
$path = $fooArray[$pid][$pid][$id];
This is my best attempt
function rcr(&$fooArray, $ids, $path, $i = 0) {
if ($ids and count($ids) > 0) {
foreach( $ids as $id ) {
$subids = // function that gets our array of subids
$subkeys = array_fill_keys($subids);
if ($i == 0) {
$fooArray[$id] = $subkeys;
$path = &$fooArray[$id];
} else {
$path[$id] = $subkeys;
$path = &$path[$id];
}
$s = $i + 1;
function rcr($fooArray, $subids, $path, $s);
}
}
}
function get_rcr() {
$fooArray = array(2 => array(), 14 => array(), 8 => array());
$ids = array(2, 14, 8);
$path = "";
rcr($fooArray, $ids, $path, $i = 0);
return $fooArray;
}
But on the second run of the function, $path[$id] fails to add to the main $fooArray
The desired result is
array(
[2] => array(
[5] => array(
[7] => array(
[46] => array()
)
),
[108] => array()
),
[14] => array(),
[8] => array(
[72] => array()
)
)
So how?