码迷,mamicode.com
首页 > 其他好文 > 详细

构造无限层级树形菜单

时间:2018-08-31 01:24:18      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:turn   time   构造   func   pre   group   create   cti   value   

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

  

构造无限层级树形菜单

标签:turn   time   构造   func   pre   group   create   cti   value   

原文地址:https://www.cnblogs.com/huixuexidezhu/p/9563446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!