2016-07-27 73 views
2

我想製作一些類似於線索數據的數據,因此數據以樹視圖顯示,但存在問題,數據顯示不正確,能否給我有人建議?如何使用Codeigniter在遞歸數據中創建層次父親子女

這裏我表

+-------------+--------------------+----------------------------------+ 
| division_id | division_parent_id | division_name     | 
+-------------+--------------------+----------------------------------+ 
| 1   | 0     | division one      | 
+-------------+--------------------+----------------------------------+ 
| 2   | 1     | division one child one   | 
+-------------+--------------------+----------------------------------+ 
| 3   | 1     | division one child two   | 
+-------------+--------------------+----------------------------------+ 
| 4   | 2     | division grandchild one-one  | 
+-------------+--------------------+----------------------------------+ 
| 5   | 2     | division grandchild one-two  | 
+-------------+--------------------+----------------------------------+ 
| 6   | 3     | division grandchild two-one  | 
+-------------+--------------------+----------------------------------+ 
| 7   | 3     | division grandchild two-two  | 
+-------------+--------------------+----------------------------------+ 
| 8   | 4     | division greatgradchild one-one | 
+-------------+--------------------+----------------------------------+ 
| 9   | 4     | division greatgrandchild one-two | 
+-------------+--------------------+----------------------------------+ 

和我的代碼

function getThreaded($row){ 

     $result = "<ul>"; 
     $result .= "<li>".$row['division_name']."</li>"; 

     $q = $this->db->get_where('tb_m_division', array('division_parent_id' => $row['division_id'])); 

     if($q->num_rows() > 0) 
     { 

      foreach($q->result_array() as $row) 
      { 
       $result .= $this->getThreaded($row); 
      } 


     } 

     $result .="</ul>"; 

     return $result; 


    } 

    function prepare(){ 


     $q = $this->db->get_where('tb_m_division', array('division_parent_id' => '0')); 

     foreach($q->result_array() as $row) 
     { 
      $result = $this->getThreaded($row); 
     } 

     // $this->load->view('header'); 
     // $this->load->view('v_tree', $data); 
     // $this->load->view('footer'); 


     echo $result; 


    } 

數據顯示僅在過去inputed,如果我添加新的數據,則另一個數據沒有顯示。

回答

0

您需要一個遞歸函數。喜歡的東西:

function getDivisions($parent_id = 0) 
{ 
    $result = ''; 
    $this->db->where('division_parent_id', $parent_id); 
    $query = $this->db->get('tb_m_division', 0); 
    if ($query->num_rows() > 0) 
    { 
     $rows = $result_array(); 

     $result = "<ul>"; 

     foreach($rows as $row) 
     { 
       $result .= "<li>".$row['division_name']."</li>"; 

       // get children 
       $result .= $this->getDivision($row['division_id']); 

      $result .= "</ul>"; 
     } 
    } 
    return $result; 
} 

我沒有測試的代碼,所以它可能是馬車,但這個想法是,函數調用自身得到各行的孩子。

希望幫助,

保羅

PS。如果您需要獲得不同類別到孩子們剛剛經歷給函數發送電平計數器太多,所以水平= 1是最高級別,級別= 2是孩子,3級是孫子。然後根據設定的水平改變李氏線。