Re: Static array causing problem in recursion

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2009/12/4 Midhun Girish <midhungirish@xxxxxxxxx>
>
> Hello guys,
> I was trying to use a recursive function to do a tree traversal.. i used a
> static array to store the nodes at each recursion.. The function works
> correctly if it is called only once during an execution.. but when i call it
> twice or more, the nodes get appended to the array...hers the var dump of
> the array...
> Three:Array ( [0] => W4 )
> Two:Array ( [0] => W4 [1] => W3 [2] => W4 )
> One:Array ( [0] => W4 [1] => W3 [2] => W4 [3] => W2 [4] => W3 [5] => W4 )
>
> I tried to reset() the array and all but not working..i am not able to
> chnage the index of the $rootsarray  back to 0... the new elelnts are added
> at the end only...can anyone give me a push in the right direction?? Im
> using PHP Version 5.2.9 in XAMPP... Hers the source...
>
>    public function getAllChildren($node,$level)
>    {
>        static $rootsarray=array();
>        static $levelcount;
>        $levelcount=$level;
>        $child=self::getChild($node);
>        if($child==''||$levelcount==0)
>        {
>            return 1;
>        }
>        else
>        {
>            $levelcount--;
>            $rootsarray[]=$child;
>            self::getAllChildren($child,$levelcount);
>        }
>        return $rootsarray;
>
>    }
>
> Midhun Girish

Of course. The array is static. So the content is maintained between calls.

You need to know when to initialize it.

Something like ...

 public function getAllChildren($node,$level,$firstCall=True)
   {
       static $rootsarray=array();
       static $levelcount;
       if($firstCall) {
           $rootsarray=array();
       }
       $levelcount=$level;
       $child=self::getChild($node);
       if($child==''||$levelcount==0)
       {
           return 1;
       }
       else
       {
           $levelcount--;
           $rootsarray[]=$child;
           self::getAllChildren($child,$levelcount,False);
       }
       return $rootsarray;

   }


--
-----
Richard Quadling
"Standing on the shoulders of some very clever giants!"
EE : http://www.experts-exchange.com/M_248814.html
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling

-- 
PHP Windows Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [PHP Users]     [PHP Database Programming]     [PHP Install]     [Kernel Newbies]     [Yosemite Forum]     [PHP Books]

  Powered by Linux