递归tree 结构

2020-08-15  本文已影响0人  xueyueshuai

    <?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]);
            }
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读