代码点火器中的递归函数


Recursion function in codeigniter

我制作了一个递归函数,以树的形式显示导航方案我在codeigniter中使用递归,但这会导致错误,因为我的代码是未定义的函数


    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'; } }
我将根和平面数组传递给这个函数,得到了未定义的行为。。在代码点火器控制器中递归调用函数的正确方法是什么错误::致命错误:调用未定义的函数parseAndPrintTree()

如果您在控制器或模型中使用此函数,则该函数是一个类方法,需要按原样调用,即使用$this->parseAndPrintTree($child,$tree):

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

否则,正如Valeh已经说过的那样,函数需要成为内部助手。创建一个助手,比如helpers/site_helper.php:

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

您现在可以使用它:

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

需要进行exists检查,以避免在多次调用助手时出现"函数已定义"错误。

我得到了解决方案,我只需要使用$this,而不仅仅是函数名


    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'; } }