PHP递归实现无限极分类

实现无限极分类的放哪广发有很多,这里介绍的是递归方法。

准备测试数组:

$cates = array(
    array(
        'id' => 1,
        'pid'   =>  0,
        'title' =>  'php'
        ),
    array(
        'id' => 2,
        'pid'   =>  0,
        'title' =>  'linux'
        ),
    array(
        'id' => 3,
        'pid'   =>  0,
        'title' =>  'mysql'
        ),
    array(
        'id' => 4,
        'pid'   =>  1,
        'title' =>  'array'
        ),
    array(
        'id' => 5,
        'pid'   =>  1,
        'title' =>  'string'
        ),
    array(
        'id' => 6,
        'pid'   =>  2,
        'title' =>  'nginx'
        ),
    array(
        'id' => 7,
        'pid'   =>  4,
        'title' =>  'array_rand'
        ),
    );

组合:一维数组

function get_cate_list($cates, $pid = 0, $level = 0, $html = '|--'){
    $temp = array();
    foreach ($cates as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level + 1;
            $v['html'] = str_repeat($html, $level + 1);
            $temp[] = $v;
            $temp = array_merge($temp, get_cate_list($cates, $v['id'], $level + 1, $html));
        }
    }
    return $temp;
}

组合:多维数组

function get_cate_list_multi($cates, $pid = 0){
    $temp = array();
    foreach ($cates as $v) {
        if ($v['pid'] == $pid) {
            $v['child'] = get_cate_list_multi($cates, $v['id']);
            $temp[] = $v;
        }
    }
    return $temp;
}

给定父id获取所有子分类

function get_cate_son($cates, $pid = 0){
    $temp = array();
    foreach ($cates as $v) {
        if ($v['pid'] == $pid) {
           $temp[] = $v;
           $temp = array_merge($temp, get_cate_son($cates, $v['id']));
        }
    }
    return $temp;
}

给定子分类的id获取所有父分类:适用于面包屑导航

function get_cate_parent($cates, $id){
    $temp = array();
    foreach ($cates as $v) {
        if ($v['id'] == $id) {
            $temp[] = $v;
            $temp = array_merge(get_cate_parent($cates, $v['pid']), $temp);
        }   
    }
    return $temp;
}
/* 打印结果 */
$all = get_cate_list($cates);
// $all = get_cate_list_multi($cates);
// $son = get_cate_son($cates, 1);
// $parent = get_cate_parent($cates, 7);

print_r($all);
// print_r($son);
// print_r($parent);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值