美文网首页
递归tree 结构

递归tree 结构

作者: xueyueshuai | 来源:发表于2020-08-15 15:41 被阅读0次

    <?php

namespace app\api\lib;

class ListToTree
{
    public static $list = [];
    public static $start_pid = 0;
    public static $var_id = 'id';
    public static $var_pid = 'pid';
    public static $var_children = 'children';

    public static function main($list, $start_pid = 0, $var_id = 'id', $var_pid = 'pid', $var_children = 'children')
    {
        self::$list = $list;
        self::$start_pid = $start_pid;
        self::$var_id = $var_id;
        self::$var_pid = $var_pid;
        self::$var_children = $var_children;


        return self::getChildren($start_pid);
    }


    public static function getChildren($pid)
    {
        $children = [];
        foreach (self::$list as $v) {
            if ($v[self::$var_pid] == $pid) {
                $obj = $v;
                $objChildren = self::getChildren($obj[self::$var_id]);
                if ($objChildren) {
                    $obj[self::$var_children] = $objChildren;
                }
                $children[] = $obj;
            }
        }
        return $children;
    }
}

<?php

namespace app\api\lib;

class TreeToList
{

    public static $tree = [];
    public static $start_pid = 0;
    public static $var_id = 'id';
    public static $var_pid = 'pid';
    public static $var_children = 'children';
    public static $list = [];

    public static function main($tree, $start_pid = 0, $var_id = 'id', $var_pid = 'pid', $var_children = 'children')
    {
        self::$tree = $tree;
        self::$start_pid = $start_pid;
        self::$var_id = $var_id;
        self::$var_pid = $var_pid;
        self::$var_children = $var_children;

        self::$list = [];

        self::everyoneToList($tree, $start_pid);

        return self::$list;
    }

    public static function everyoneToList($list, $pid)
    {
        foreach ($list as $v) {
            $obj = $v;
            unset($obj[self::$var_children]);
            $obj[self::$var_pid] = $pid;

            self::$list[] = $obj;

            if ($v[self::$var_children]) {
                self::everyoneToList($v[self::$var_children], $v[self::$var_id]);
            }
        }
    }
}

相关文章

网友评论

      本文标题:递归tree 结构

      本文链接:https://www.haomeiwen.com/subject/uwjadktx.html