PHP无限级分类查找父层函数

本文介绍了一种用于无限级分类查询的算法实现,通过递归函数findFather()来查找节点的父级、祖先及完整的家谱信息。适用于多层次的数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 如:

classID          classFID          className          classCount
      1                  0                   中国                     0
      2                  1                   浙江                     0
      3                  1                   江苏                     0
      4                  2                   杭州                     0
      5                  4                  西湖区                   0

findFather('4','0') 显示 => 杭州

findFather('4','1') 显示 => 浙江

findFather('4','2') 显示 => 中国

findFather('4','3') 显示 => 中国 -> 浙江 -> 杭州

代码如下:

    // ========== findFather函数 START ==========
    // 功能:无限级分类之找出父层的相关数据
    // 参数:$classID,当前子层的编号
    //          $type,0找自己 1找父亲 2找祖先 3找家谱
    // 字段:classID主键,自生成 classFID父编号
    //          className分类名称 classCount分类统计

    function findFather($classID,$type)
    {
        
global $db,$flist,$forefather;
        
define("_STR_CUT", " -> ");

        
$db->query("set names 'utf8'");
        
$sql         = 'select * from tbl_name where classID = "'.$classID.'"';
        
$result         = $db->query($sql);
        
$recordCount = $result->num_rows;
        
if ($recordCount != 0)
        {
            
//取值
            $row       = $result->fetch_assoc();
            
$classFID  = $row['classFID'];
            
$classID   = $row['classID'];
            
$className = $row['className'];

            
//若找到祖先,即classFID为0,则将函数状态设为0
            if ($classFID == '0'$type='0';
        }
        
        
if ($type == '1'//找父亲
        {
            
$type = '0'//第二次开始函数状态为0,即循环2次
            findFather($classFID,$type);
        }
        
else if ($classFID != '0' AND $type == '2'//找祖先,状态type为2,祖先classFID不为0未找到
        {
            findFather(
$classFID,$type);
        }
        
else if ($type == '3')
        {
            findFather(
$classFID,$type);
            
$flist = $flist . _STR_CUT . $className//生成家谱
        }
        
else if ($type == '0')
        {
            
$forefather = $className;
        }

        
$result = $forefather . $flist;
        
return $result;
        
    }
    
// ========== findFather函数 END ==========
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值