Home > Backend Development > PHP Tutorial > PHP array to tree structure and tree structure to array

PHP array to tree structure and tree structure to array

藏色散人
Release: 2023-04-09 18:36:01
forward
2359 people have browsed it

Recommended: "PHP Video Tutorial"

public function index()
    {
        $data = [
            [
                'id'=>1,
                'parent_id' => 0,
                'name' => '第一个'
            ],

            [
                'id'=>2,
                'parent_id' => 0,
                'name' => '第二个'
            ],

            [
                'id'=>3,
                'parent_id' => 1,
                'name' => '第三个'
            ],

        ];
        $r = $this->list_to_tree($data);
        dump($r);
    }
Copy after login

PHP array to tree structure and tree structure to array

Array to tree structure

#
function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'parent_id', $child = 'children'){
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = 0;
            if (isset($data[$pid])) {
                $parentId = $data[$pid];
            }
            if ((string)$root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;}
Copy after login

#tree Convert structure to array

#
function tree_to_list($tree = [], $children = 'children'){
    if (empty($tree) || !is_array($tree)) {
        return $tree;
    }
    $arrRes = [];
    foreach ($tree as $k => $v) {
        $arrTmp = $v;
        unset($arrTmp[$children]);
        $arrRes[] = $arrTmp;
        if (!empty($v[$children])) {
            $arrTmp = tree_to_list($v[$children]);
            $arrRes = array_merge($arrRes, $arrTmp);
        }
    }
    return $arrRes;}
Copy after login

The above is the detailed content of PHP array to tree structure and tree structure to array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template