阅读 87

PHP递归

 //模型公众方法,递归

    public function treeLevel(array $data, int $pid = 0, string $html = '--', int $level = 0)

    {

        //静态数组不在方法内,所以无法覆盖

        static $arr = [];



        foreach ($data as $val) {

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

                $val['html'] = str_repeat($html, $level * 2);

                $val['level'] = $level + 1;

                //如果是0,则是顶级菜单

                $arr[] = $val;

                $this->treeLevel($data, $val['id'], $html, $val['level']);

            }

        }



        return $arr;



    }





    //递归处理层

    public function sonLevel($data, $pid = 0)

    {

        $arr = [];

        foreach ($data as $val){

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

                $val['son'] = $this->sonLevel($data,$val['id']);

                $arr[] = $val;

            }

        }



        return $arr;

    }
复制代码
文章分类
后端
文章标签