0

ツリー形式でナビゲーション スキームを表示する再帰関数を作成しました。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() への呼び出し

4

2 に答える 2

1

これをコントローラーまたはモデル内で使用している場合、関数はクラスメソッドであり、そのように呼び出す必要があります。つまり、次を使用し$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);

ヘルパーが複数回呼び出された場合に「関数は既に定義されています」というエラーが発生しないようにするには、存在チェックが必要です。

于 2012-07-14T12:41:05.417 に答える
0

関数名だけでなく $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'; } }
于 2012-07-19T10:53:10.697 に答える