PHP无限极树状型分类

无限极分类封装方法:

if(! function_exists('treeCategory'))
{
  
    /**
     * @param array $datas                   原数组
     * @param int $parent                    默认父级id=0
     * @param string $key                    条件子级字段
     * @param string $leaf                   条件父级字段
     * @param string|null $sortColumn        表中需要排序的字段  默认空   
     * @param int $order                     SORT_ASC默认升序  SORT_DESC降序
     * @param int $maxDeep                   设置最大层级
     * @param array $nullLeaf                
     * @param int $deep                      默认层级0
     * @return array
     */
    
    function treeCategory( array $datas, $parent = 0, string $key = 'id', string $leaf = "parentId", string $sortColumn = null, $order = SORT_ASC, $maxDeep = 99, array &$nullLeaf = [], int $deep = 0 )
    {
        $tree = [];
        $leafs = array_column($datas, $leaf);
        if( in_array($parent, $leafs) ) {
            $deep++;
            if( $maxDeep !== -1 && $deep <= $maxDeep ) {
                if( !isset($nullLeaf[$deep]) )
                    $nullLeaf[$deep] = [
                        'deep' => $deep,
                        'nullLeaf' => [],
                    ];
                foreach ( $datas as $data ) {
                    if( $data[$leaf] != $parent )
                        continue;
                    $tree[$data[$key]] = $data;
                    $tree[$data[$key]]['deep'] = $deep;
                    $tree[$data[$key]]['children'] = toTree( $datas, $data[$key], $key, $leaf, $sortColumn, $order, $maxDeep, $nullLeaf, $deep );
                    if( count($tree[$data[$key]]['children']) == 0 )
                        $nullLeaf[$deep]['nullLeaf'][] = $data[$key];
                }
                if( !empty( $sortColumn ) )
                    if( count($tree) > 0 )
                        array_multisort(array_column($tree, $sortColumn), $order, $tree);
            }
        }
        return $tree;
    }
}


使用: $tree = treeCategory($goodsTypes, 0, 'id', 'parentId', 'sort', SORT_ASC, 3);

返回数据以权限列表示例:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值