2012-09-27 63 views
-1

我嘗試創建樹recursivelly的數組,但它顯示我的冗餘錯誤,代碼錯誤創建樹的陣列遞歸

private function printChildQuestions($parentid, $level=0) { 
    $categorias = Categoria::model()->findAll("id_pai =".$parentid); 

     foreach($categorias as $c){ 

      $space = str_repeat(' -&nbsp &nbsp ', $level); 

      $flag=0; 
      foreach($c->produtos as $p){ 

       $GLOBALS['children'][] = array("data" => $p->nome,"metadata" => array("id" => $p->id)); 

       $flag=1;  
      } 
      if($flag == 1){ 
       $GLOBALS['arvore'][] = array("data" => $c->nome,"metadata" => array("id" => $c->id) ,"children" => $GLOBALS['children']); 
      } 

      $GLOBALS['arvore'][] = array("data" => $c->nome,"metadata" => array("id" => $c->id)); 

      unset($GLOBALS['children']); 
      $this->printChildQuestions($c->id,$level+1); 
     } 

} 

函數的調用$這個 - > printChildQuestions(0);

其返回我的這些值:

produtos  ---- ok 
    produto1  ---- ok 
produtos  ---- wrong line , repeated 1st line 
subprodutos ---- ok 
    produto 2 ---- ok 
subprodutos ---- wrong line , repeated 4th line 
subsubprodutos ---- ok 
    produr 3  ---- ok 
    produto 3.2 ---- ok 
subsubprodutos ---- wrong line, repeated 7th line 
produtos3.1 ---- ok 
produto 2.2 ---- ok 
produtos1.2 ---- ok 

正確的是

produtos  ---- ok 
    produto1  ---- ok 
subprodutos ---- ok 
    produto 2 ---- ok 
subsubprodutos ---- ok 
    produr 3  ---- ok 
    produto 3.2 ---- ok 
produtos3.1 ---- ok 
produto 2.2 ---- ok 
produtos1.2 ---- ok 
+0

值應該如何? – dbf

+0

噢,是的,這在評論中看起來非常清楚,請將其移至您的問題? – dbf

回答

0

如果在第一層(0級)你有重複的第一行$categorias = Categoria::model()->findAll("id_pai =".$parentid);是被指責。對於parentid = 0,它會給你重複。

+0

第一個id是1,只是第一行有一個id_pai = 0 –

+0

你的代碼很簡單。你用'$ this-> printChildQuestions(0);''來調用它因此,您的方法$ parentid的第一個參數是0. findAll需要id_pai = parentid(在您的情況下爲0)。你有foreach。從你粘貼的findAll爲id = pai = 0返回重複。它與你的復發無關(乍一看看起來不錯)。 –