PHP递归算法获取树形菜单数据TreeMenu代码实现

  • Post author:
  • Post category:技术

点击数:2057

php递归算法获取树形菜单数据TreeMenu代码实现

本文地址http://yangjianyong.cn/?p=271转载无需经过作者本人授权

原始的数据格式,默认顶级菜单的父级菜单id为0

[
    {
        "id" : 1,
        "name" : "menu1",
        "parent_id" : 0
    },
    {
        "id" : 2,
        "name" : "menu2",
        "parent_id" : 0,
    },
    {
        "id" : 3,
        "name" : "menu1-1",
        "parent_id" : 1
    }
]

输出数据格式为树形的json格式

[
    {
        "id" : 1,
        "name" : "menu1",
        "parent_id" : 0,
        "children" : [
            {
                "id" : 3,
                "name" : "menu1-1",
                "parent_id" : 1,
                "children" : []
            }
        ],
    },
    {
        "id" : 2,
        "name" : "menu2",
        "parent_id" : 0,
        "children" : []
    }
]

php代码实现递归算法

/**
   * 获取树形菜单
   * @param array $menu
   * @param int $parentId
   * @return array
   */
public function getTreeMenu(array $menu , int $parentId){
    $tree = [];
    foreach ($menu as $k => $v) {
        $tmp = [];
        $tmp['name'] = $v['name'];
         $tmp['id'] = $v['id'];
        $tmp['parentId'] = $v['parent_id'];
        $tmp['children'] = $this->getTreeMenu($menu, $v['id']);
        $tree[] = $tmp;
    }
    return $tree;
}

欢迎来我的博客逛一逛 杨建勇的个人博客http://yangjianyong.cn