树的输出到字符串

问题描述 投票:0回答:1

我的桌子

[cat_id,title,pid]
。我需要按以下格式获取所有子子类别 ID:

[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,获得所有这些物品。

我尝试执行以下代码,但它不起作用:

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

也许有更好的方法?

php codeigniter recursion tree
1个回答
0
投票

尝试下面的代码来获取给定父 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;

}
© www.soinside.com 2019 - 2024. All rights reserved.