PHP 递归函数

2020-05-15  本文已影响0人  farlamp

1.直接显示没有层级显示区别

public function tree($userinfo, $id, &$children, $ds = 0, $level = 0)

    {

        if (!$id) {

            return 'parent_id is null';

        }

        $level++;

        foreach ($userinfo as $key => $value) {

            if ($ds) {

                if ($level > $ds) continue;

            }

            if ($value['parent_id'] == $id) {

                $children[] = ['id' => $value['id'], "parent_id" => $value['parent_id'], "level" => $level];

                // $children[] = $value['id'].$value['parent_id'];

                $this->findBottoms($userinfo, $value['id'], $children, $ds, $level);

            }

        }

        return $children;

    }

2.有明显的层级区分

 public function tree($arrCat, $pid = 0, $dj = 0)

    {

        $child = ["sum" => 0, 'uid' => $pid];   // 定义存储子级数据数组

        foreach ($arrCat as $key => $value) {

            if ($value['pid'] == $pid) {

                $child['sum'] += $this->model->where(['id' => $value['id']])->value('money');

                unset($arrCat[$key]);  // 使用过后可以销毁

                $value['child'] = $this->tree_levle($arrCat, $value['id']);   // 递归调用,查找当前数据的子级

                $child[] = $value;   // 把子级数据添加进数组

            }

        }

        return $child;

    }

上一篇 下一篇

猜你喜欢

热点阅读