当前位置 博文首页 > fareast_mzh的博客:查找所有子业务id 递归转化为循环

    fareast_mzh的博客:查找所有子业务id 递归转化为循环

    作者:[db:作者] 时间:2021-08-13 15:54

        /**
         * 查找所有子业务id(多级)
         * @param $id
         * @param $allIds
         */
        public static function getChildIds($id, &$allIds) {
            /** @var $query \Illuminate\Database\Eloquent\Builder */
            $query = self::where("parent_id", "=", $id);
            $rows = $query->get(['id', 'parent_id', 'name'])->all();
            foreach ($rows as $row) {
                $thisId = $row->getAttribute("id");
                /** @var $row Business */
                array_push($allIds, $thisId);
                self::getChildIds($thisId, $allIds);
            }
        }
    
        public static function getChildIdsNR($id) {
            $stack = array();
            $rows = self::where("parent_id", "=", $id)->get(['id', 'parent_id', 'name'])->all();
            if (!empty($rows)) {
                array_push($stack, $rows[0]);
            }
            $childIds = array();
            $i = 1;
            while (!empty($stack)) {
                $top = array_pop($stack);
                // 异常情况 上级id与这级id一样
                if ($top->id == $id) {
                    break;
                }
                $children = self::where("parent_id", "=", $top->id)->get(['id', 'parent_id', 'name'])->all();
                array_push($childIds, $top->id);
                if (empty($children)) {
                    if (isset($rows[$i])) {
                        array_push($stack, $rows[$i]);
                        $i += 1;
                    }
                } else {
                    foreach ($children as $child) {
                        array_push($stack, $child);
                    }
                }
            }
            return $childIds;
        }

    Usage:

    // $businessIds = [];
    // Business::getChildIds($this->businessId, $businessIds);
    $businessIds = Business::getChildIdsNR($this->businessId);

    照着这里套

    按层级遍历二叉树

    phpstorm?无限重复试用

    cs
    下一篇:没有了