0

i have made a recursion function to show navigation scheme in tree form i am using recursion in codeigniter but this gives error as un-defined function my code is


    function parseAndPrintTree($root, $tree) 
      {
       $return = array();
       if(!is_null($tree) && count($tree) > 0) 
         {
          echo 'ul';
           foreach($tree as $child => $parent) 
            {
            if($parent == $root) 
              {
unset($tree[$child]); echo 'li'.$child; return parseAndPrintTree($child, $tree); // Recursion-here(Not called) echo 'closing li'; } } echo 'closing ul'; } }
i passed root and flat array to this function and got undefined behaviour.. what is right way to call function recursively in code-igniter controller Error:: Fatal error: Call to undefined function parseAndPrintTree()

1
  • Where is the function located? Commented Jul 14, 2012 at 11:33

2 Answers 2

1

If you're using this inside a controller or a model the function is a class method, and needs to be called as such, i.e. using $this->parseAndPrintTree($child,$tree) :

...
if($parent == $root) 
{
 unset($tree[$child]);
 echo 'li'.$child;
      $this->parseAndPrintTree($child, $tree);
      // ^-- inside the recursion
 echo 'closing li';
}
...

Otherwise functions, as already said by Valeh, need to be inside helpers. Create an helper, say helpers/site_helper.php:

if(!function_exists('parseAndPrinTree')
{
  function parseAndPrintTree($root, $tree)
  {}
}

You can now use it with:

$this->load->helper('site');
parseAndPrintTree($root,$tree);

the exists check is needed to avoid getting a "function already defined" error in case the helper gets called more than once.

Sign up to request clarification or add additional context in comments.

Comments

0

I got the solution simply i need to use $this instead of just function name


    function parseAndPrintTree($root, $tree) 
      {
       $return = array();
       if(!is_null($tree) && count($tree) > 0) 
         {
          echo 'ul';
           foreach($tree as $child => $parent) 
            {
            if($parent == $root) 
              {

unset($tree[$child]); echo 'li'.$child; $this->parseAndPrintTree($child, $tree); // Recursion-here(Now called) echo 'closing li'; } } echo 'closing ul'; } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.