Yii2无限分类-category level

Yii2无限分类

<?php 
/*
 * 无限极分类 类
 */
namespace common\components;
header("Content-Type: text/html; charset=UTF-8");
Class TreeClass {
    //组合一维数组
    Static Public function unlimitedForLevel ($cate, $html = '|---', $parent_id = 0, $level = 0) {
        $arr = array();
        foreach ($cate as $k => $v) {
            // print_r($v);die;
            if ($v['parent_id'] == $parent_id) {
                $v['level'] = $level + 1;
                $v['html']  = str_repeat($html, $level);
                $v['name']  =   $v['html'].$v['name'] ;
                $arr[] = $v;
                $arr = array_merge($arr, self::unlimitedForLevel($cate, $html, $v['id'], $level + 1));
            }
        }
        return $arr;
    }
    //组合多维数组
    Static Public function unlimitedForLayer ($cate, $name = 'child', $parent_id = 0) {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $parent_id) {
                $v[$name] = self::unlimitedForLayer($cate, $name, $v['id']);
                $arr[] = $v;
            }
        }
        return $arr;
    }
    //传递一个子分类ID返回所有的父级分类  
    Static Public function getParents ($cate, $id) {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['id'] == $id) {
                $arr[] = $v;
                $arr = array_merge(self::getParents($cate, $v['parent_id']), $arr); 
            }
        }
        return $arr;
    }
    //传递一个父级分类ID返回所有子分类ID
    Static Public function getChildsId ($cate, $parent_id) {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $parent_id) {
                $arr[] = $v['id'];
                $arr = array_merge($arr, self::getChildsId($cate, $v['id']));
            }
        }
        return $arr;
    }
    //传递一个父级分类ID返回所有子分类
    Static Public function getChilds ($cate, $parent_id) {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $parent_id) {
                $arr[] = $v;
                $arr = array_merge($arr, self::getChilds($cate, $v['id']));
            }
        }
        return $arr;
    }
}
// $cate = array(
//     0 => array('id' => 1, 'parent_id' => 0, 'name' => '江西省'),
//     1 => array('id' => 2, 'parent_id' => 0, 'name' => '浙江省'),
//     2 => array('id' => 3, 'parent_id' => 1, 'name' => '上饶市'),
//     3 => array('id' => 4, 'parent_id' => 3, 'name' => '广丰县'),
//     4 => array('id' => 5, 'parent_id' => 2, 'name' => '杭州市'),
//     5 => array('id' => 6, 'parent_id' => 5, 'name' => '西湖'),
//     6 => array('id' => 7, 'parent_id' => 6, 'name' => '断桥'),
//  );
// print_r(Category::unlimitedForLevel($cate));
// print_r(Category::unlimitedForLayer($cate));
//print_r(Category::getParents($cate,7));
//print_r(Category::getChildsId($cate,2));
//print_r(Category::getChilds($cate,2));

?>

Previous Post电商广告图常用设计技巧剖析
Next PostYii2 response 返回 JSONP callback