I have a category tree in XML like
<cat name='cat_1' id='1'>
<cat name='cat_2' id='2'>
<cat name='cat_3' id='3'>
</cat>
</cat>
<cat name='cat_4' id='4'>
<cat name='cat_5' id='5'>
<cat name='cat_6' id='6'>
<cat name='cat_7' id='7'>
</cat>
</cat>
</cat>
</cat>
</cat>
now I want to implement code such that I can travers this tree an find categories ids by the name i.e. If input is cat_6 than result should be 6;
What I have done
$xmlCatTree // is my simple xml object
class MyClass{
public function traverseForId($cat_name , $xmlCatTree )
{
if($xmlCatTree->attributes()->name == $cate_name)
{
return $xmlCatTree->attributes()->id;
}
if(count($item->children())>0){
foreach($item->children() as $child)
{
return $this->traverseForId($cat_name,$child);
} }
}
}
It works perfectly for single branch i.e child nodes of cat_2 will have correct results but if I search for cat_7 nothing will return. I thing It happens due to branched recursion. I want to know how to cop this.