2012-07-30 60 views
0

我的表[cat_id,title,pid]。我需要讓所有的孩子子類ID`s採用以下格式:樹的輸出爲字符串

[1] =>Array ([cat_id] => 2 [title] => TEST [pid] => 1), 

[2] =>Array ([cat_id] => 3 [title] => TEST [pid] => 1), 

[3] =>Array ([cat_id] => 4 [title] => TEST [pid] => 2), 

[4] =>Array ([cat_id] => 5 [title] => TEST [pid] => 3) 

目的 - 用孩子的的ID`s,讓所有這些項目。

我試圖做一些如下面的代碼,但它不工作:

public function get_ids($tree,$cid = 0) 
{ 

    $data = $this->db->select('cat_id, title, pid') 
        ->where('pid',$cid) 
        ->get('catalog'); 

    $result = array_push($tree,$data->result_array()); 

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

     foreach ($data->result_array() as $r) { 

      return $this->get_ids($result,$r['cat_id']); 

     } 
    } 
    else{ 
     return $result; 
    } 
} 

也許有更好的辦法?

回答

-1

請嘗試下面的代碼,通過給定的父ID來獲取所有子ID。

function fnGetChildCatelogs($id) { 

    $qry = "SELECT cat_id FROM catalog WHERE pid = $id"; 

    $rs = mysql_query($qry);  

    $arrResult = array();  

    if(mysql_num_rows($rs) > 0) { 

     # It has children, let's get them. 

     while($row = mysql_fetch_array($rs)) { 

      # Add the child to the list of children, and get its subchildren 

      $arrResult[$row['cat_id']] = fnGetChildCatelogs($row['cat_id']); 

     } 

    } 

    return $arrResult; 

} 
+0

它的工作完美!非常感謝! – martiniti 2012-07-30 11:51:22

+1

這可能會給你的概念想法,但請不要使用此代碼。 Codeigniter爲您提供了一種更好(更安全!)的查詢數據庫的方式。 – Robert 2012-07-30 12:18:00

+0

這是一個遞歸的通用代碼。在投票之前可以添加代碼點火器功能。 – Codesen 2012-07-30 12:33:05