查找所有子业务id 递归转化为循环
  TEZNKK3IfmPf 2024年03月22日 95 0
    /**
     * 查找所有子业务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 无限重复试用

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年03月22日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2023年11月14日   11   0   0 二叉树C++
  TEZNKK3IfmPf   2023年11月15日   11   0   0 二叉树
  TEZNKK3IfmPf   2023年11月14日   19   0   0 二叉树java
TEZNKK3IfmPf