超级简单PHP无限极分类,PHP将列表转为树状结构


原文地址:超级简单PHP无限极分类,PHP将列表转为树状结构

分享一个超级简单PHP无限极分类,PHP将列表转为树状结构。

function getTree($list, $key = 'pid', $pid = 0)
    {
        $tree = [];
        foreach ($list as $v) {

            if ($v[$key] == $pid) {
                $children = getTree($list, $key, $v['id']);
                if (count($children) > 0) {
                    $v['children'] = $children;
                }
                $tree[] = $v;
            }
        }

        return $tree;
    }

递归select,option列表

function optionCategory($arr,$parent = 0,$level = 0){
        $html = '    ';
        $options = [];
        $func = __FUNCTION__;
        foreach($arr as $v){
            if($v['parent'] === $parent){
                $code = $func($arr,$v['id'],$level+1);
                $options[] = [
                    'id' => $v['id'],
                    'name' => str_repeat($html,$level).$v['category_name'],
                    'parent' => $v['parent'],
                    'slug' => $v['category_slug']
                ];

                $options = array_merge($options,$code);
            }
        }
        return $options;
    }
/**
     * 获取该分类下的所有子分类 返回一个数组集
     */
    function getChildArr($parentId,$arr){
        $func = __FUNCTION__;
        $allChild = [];
        foreach($arr as $key => $v){
            if($v['parent'] == $parentId){
                $code = $func($v['id'],$arr);
                $allChild[] = $v['id'];

                $allChild = array_merge($allChild,$code);
            }
        }
        return $allChild;
    }

    /**
     * 获取该分类的父级分类 祖先分类
     */
    function getParents($arr,$child){
        $result = [];
        $func = __FUNCTION__;
        foreach($arr as $parent){
            if($child['parent'] === $parent['id']){
                array_push($result,$parent['id']);
            }
        }
        return $result;
    }

 

评论

登录后评论

服务器优惠活动

Top