I have an ordered array so that each ref
key is guaranteed to exist among the former elements in the same array. However, the reference might be inside another array in a former element. So I'm using a recursive function to find the appropriate place, but for some reason I can not delete the former element.
What I can do: Copy necessary elements to where they belong
What I can not do: Move these elements across arrays
Here's a pseudo output of the original array.
Array
(
[0] => Array
(
[id] => 1
[ref] =>
[arr] => Array ()
)
[1] => Array
(
[id] => 2
[ref] => 1
[arr] => Array ()
)
[2] => Array
(
[id] => 3
[ref] => 1
[arr] => Array ()
)
[3] => Array
(
[id] => 4
[ref] => 3
[arr] => Array ()
)
)
Here's my code.
$myArr = array(/* above elements gathered from the DB */);
foreach ($myArr as &$arr) {
if (!is_null($arr['ref'])) relocate($arr, $arr['ref']);
}
unset($arr);
function relocate(&$node, $id, &$arr=NULL) {
global $myArr;
if (is_null($arr)) $arr = &$myArr;
foreach ($arr as &$arr1) {
if ($arr1['id'] == $id) {
array_push($arr1['arr'], &$node);
return;
}
}
unset($arr1); // not sure if this is necessary
if (!empty($arr['arr'])) relocate(&$node, $id, &$arr['arr']);
}
And the desired output:
Array
(
[0] => Array
(
[id] => 1
[ref] =>
[arr] => Array
(
[0] => Array
(
[id] => 2
[ref] => 1
[arr] => Array ()
)
[1] => Array
(
[id] => 3
[ref] => 1
[arr] => Array
(
[0] => Array
(
[id] => 4
[ref] => 3
[arr] => Array ()
)
)
)
)
)
)
What am I missing?