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

你可能感兴趣的:(PHP)