2

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

 2 years ago
source link: https://www.iplayio.cn/post/866220
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

发布:3个月前 更新:3个月前 folder_open 计算机编程语言 PHP编程 176 浏览 comment

原文地址:超级简单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;
    }



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK