无限分类 - 有限级控制

数据库使用的mysql具体表如下

CREATE TABLE `eb_store_category` (  
    `id` mediumint(11) NOT NULL AUTO_INCREMENT COMMENT '商品分类表ID', 
    `pid` mediumint(11) NOT NULL COMMENT '父id',  
    `name` varchar(100) NOT NULL COMMENT '分类名称',
    PRIMARY KEY (`id`),  
    KEY `pid` (`pid`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='商品分类表'

具体代码如下

//共用的类库
//主要封装了上下级关系处理
class ComUtil{
    /**
     * desc 获取子集link map
     * @param $data array
     * @param $id int
     * @param $level int 分类级联层级
     * @return array 
     */
    public static function getChildMap($data, $id = 0, $level=1)
    {
        $tree = [];
        if($level <= 0) { return $tree; }
        foreach($data as $nKey => $nItem){
            if($nItem['pid'] == $id){
                unset($data[$nKey]);
                $tree[] = [
                    'id' => $nItem['id'],
                    'name' => $nItem['name'],
                    'pid' => $nItem['pid'],
                    'children' => getChildMap($data, $nItem['id'], --$level),
                ];
            }
        }
        return $tree;
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 1
 if($level <= 0) { return $tree; }

这里有问题,只支持2级,改成下面这种

if (empty($data)) {
            return $tree;
        }
3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!