构造无限层级树形菜单

Posted huixuexidezhu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了构造无限层级树形菜单相关的知识,希望对你有一定的参考价值。

<?php
/**
 * Created by PhpStorm.
 * User: liupf
 * Date: 18-8-30
 * Time: 下午11:44
 */

function arrayConvertToTree ($array, $rootId) {
    $group = [];
    $map = [];

    foreach ($array as $val) {
        $group[$val[‘parent_id‘]][] = $val;
        $map[$val[‘id‘]] = [
            $val[‘parent_id‘],
            count($group[$val[‘parent_id‘]]) - 1
        ];
    }

    foreach ($group as $key => &$val) {
        if (!empty($map[$key])) {
            $pos = $map[$key];
            $group[$pos[0]][$pos[1]][‘children‘] = &$val;
      }
    }

    return $group[$rootId];
}

$raw_data = [
    [
        ‘id‘ =>	1,
        ‘parent_id‘ => 0,
        ‘value‘ => 1,
        ‘children‘ => []
    ],
    [
        ‘id‘ =>	2,
        ‘parent_id‘ => 1,
        ‘value‘ => 2,
        ‘children‘ => []
    ],
    [
        ‘id‘ =>	3,
        ‘parent_id‘ => 1,
        ‘value‘ => 3,
        ‘children‘ => []
    ],
    [
        ‘id‘ =>	4,
        ‘parent_id‘ => 2,
        ‘value‘ => 4,
        ‘children‘ => []
    ],
    [
        ‘id‘ =>	5,
        ‘parent_id‘ => 2,
        ‘value‘ => 5,
        ‘children‘ => []
    ],
    [
        ‘id‘ =>	6,
        ‘parent_id‘ => 3,
        ‘value‘ => 6,
        ‘children‘ => []
    ],
    [
        ‘id‘ =>	7,
        ‘parent_id‘ => 3,
        ‘value‘ => 7,
        ‘children‘ => []
    ],
    [
        ‘id‘ =>	8,
        ‘parent_id‘ => 4,
        ‘value‘ => 8,
        ‘children‘ => []
    ],
    [
        ‘id‘ =>	7,
        ‘parent_id‘ => 4,
        ‘value‘ => 7,
        ‘children‘ => []
    ]
];

$tree = arrayConvertToTree($raw_data, 0);

print_r($tree);

  

以上是关于构造无限层级树形菜单的主要内容,如果未能解决你的问题,请参考以下文章

js中实现无限层级的树形结构(类似递归)

VUE展示无限层级树形数据结构

最简单的无线分类,无限树形菜单解决方案

jstl处理递归问题+jquery,tree无限级树形菜单+简单实用案例

django-树形结构

项目开发-树形层级结构中的数量统计