Method of generating data count from PHP array (implement infinite level classification list)

Realize unlimited classification list

/**
     * 一维数据数组生成数据树
     * @param array $list 数据列表
     * @param string $id 父ID Key
     * @param string $pid ID Key
     * @param string $son 定义子数据Key
     * @return Collection
     */
    public static function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
    {
    
    
        list($tree, $map) = [[], []];
        foreach ($list as $item) {
    
    
            $map[$item[$id]] = $item;
        }

        foreach ($list as $item) {
    
    
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
    
    
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
    
    
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }

    /**
     * 一维数据数组生成数据树
     * @param array $list 数据列表
     * @param string $id ID Key
     * @param string $pid 父ID Key
     * @param string $path
     * @param string $ppath
     * @return array
     */
    public static function arr2table(array $list, $id = 'id', $pid = 'pid', $path = 'path', $ppath = '')
    {
    
    
        $tree = [];
        foreach (self::arr2tree($list, $id, $pid) as $attr) {
    
    
            $attr[$path] = "{
    
    $ppath}-{
    
    $attr[$id]}";
            $attr['sub'] = isset($attr['sub']) ? $attr['sub'] : [];
            $attr['spt'] = substr_count($ppath, '-');
            $attr['spl'] = str_repeat(" ├ ", $attr['spt']);
            $sub         = $attr['sub'];
            unset($attr['sub']);
            $tree[] = $attr;
            if (!empty($sub)) {
    
    
                $tree = array_merge($tree, self::arr2table($sub, $id, $pid, $path, $attr[$path]));
            }
        }
        return $tree;
    }

Reprinted from the comment area of ​​the laravel forum: https://learnku.com/articles/45643

Guess you like

Origin blog.csdn.net/qq_39004843/article/details/107414038