I have following array:
Array
(
[1] => 0
[2] => 1
[3] => 2
[4] => 3
[5] => 1
[6] => 0
)
keys of this array is unique, and values showing parent of key. like parent of 1 & 6 is 0, parent of 2 is 1, for 3 is 2....
I was writing a recursive function which will find the parents for given child id. (4->3->2->1->0) here is my code: but it returns no results
$child_node = 4;
function find_parents($child_node){
global $tree, $mark;
$mark[$child_node] = TRUE;
$ans = array(); //blank array for result
foreach($tree[$child_node]->children as $child)
if(!$mark[$child]){
$ans[$child]=$child;
find_parents($ans[$child],$child);
}
}
Heres is How I create the tree
class node {
var $children;
var $parents;
public function __construct(){
$this->children = array();
$this->parents = array();
}
}
$tree = array();
foreach ($a as $q => $p){
if(!isset($tree[$p]))
$tree[$p] = new node;
if(!isset($tree[$q]))
$tree[$q] = new node;
$mark[$p]=FALSE;
$mark[$q]=FALSE;
array_push($tree[$p]->children,$q);
}