php 获取父级分类id下全部的子级id

    public static function getCateIds()
    {
        //获取商品分类id
        $where = [
            ['is_disable', '=', 0],
            ['is_delete', '=', 0],
        ];
        $cate = self::field('id,pid,category,pricing_unit')->where($where)->select()->toArray();
        $cate = array_column($cate, null, 'id');
        $cate_ids = self::getResult($cate);
        unset($cate_ids[0]);
        foreach ($cate as  $v) {
            if ($v['pid'] != 0) {
                unset($cate_ids[$v['id']]);
            }else{
                if (!empty($cate_ids[$v['id']])) {
                    array_unshift($cate_ids[$v['id']], $v['id']);
                }else{
                    $cate_ids[$v['id']][] = $v['id'];
                }
            }
        }
        return $cate_ids;
    }


    public static  function getResult($categories){
        $result = [];
        // 遍历分类数组
        foreach ($categories as $category) {
            $parentId = $category['pid'];
            $categoryId = $category['id'];

            if (!isset($result[$parentId])) {
                $result[$parentId] = array();
            }
            $result[$parentId][] = $categoryId;
        }

        foreach ($result as $parentId => &$children) {
            $descendants = array();
            foreach ($children as $childId) {
                $descendants = array_merge($descendants, self::getChildren($childId,
                    $result));
            }
            $children = array_unique(array_merge($children, $descendants));
        }

        return $result;
    }


    public static function getChildren($categoryId, $categories) {
        $children = array();

        if (isset($categories[$categoryId])) {
            foreach ($categories[$categoryId] as $childId) {
                $children[] = $childId;
                $children = array_merge($children, self::getChildren($childId,
                    $categories));
            }
        }

        return $children;
    }

返回格式

 

posted @ 2024-02-02 13:31  -韩  阅读(33)  评论(0编辑  收藏  举报