php版
<?php
$list = [
[
"id" =>1,
"pid" => 0,
"level" => "小学"
],
[
"id" =>2,
"pid" => 1,
"level" => "一年级"
],
[
"id" =>3,
"pid" => 1,
"level" => "二年级"
],
[
"id" =>4,
"pid" => 2,
"level" => "一班"
],
[
"id" =>5,
"pid" => 2,
"level" => "五班"
],
[
"id" =>6,
"pid" => 3,
"level" => "三班"
],
[
"id" =>6,
"pid" => 0,
"level" => "中学"
],
[
"id" =>7,
"pid" => 6,
"level" => "一年级"
]
];
function getChildList($list,$pid = 0) {
$result = array();
foreach($list as $v){
if($v['pid'] == $pid){
$child = getChildList($list,$v['id']);
if(!empty($child)){
$v['childList'] =$child;
}
$result[] = $v;
}
}
return $result;
}
function to_tree($items, $pid = 'pid', $child = 'children')
{
$map = [];
$tree = [];
foreach ($items as &$it) {
$map[$it['id']] = &$it;
}
foreach ($items as &$it) {
$parent = &$map[$it[$pid]];
if ($parent) {
$parent[$child][] = &$it;
} else {
$tree[] = &$it;
}
}
return $tree;
}
java版
package com.zlsn.recursion;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class Menu {
@Test
public void testMenuList() {
MenuRespVO menu1 = new MenuRespVO();
menu1.setMenuName("文章管理");
menu1.setId(1);
menu1.setPid(0);
MenuRespVO menu2 = new MenuRespVO();
menu2.setMenuName("商品管理");
menu2.setId(2);
menu2.setPid(0);
MenuRespVO menu3 = new MenuRespVO();
menu3.setMenuName("文章分类");
menu3.setId(3);
menu3.setPid(1);
MenuRespVO menu4 = new MenuRespVO();
menu4.setMenuName("文章内容");
menu4.setId(4);
menu4.setPid(1);
MenuRespVO menu5 = new MenuRespVO();
menu5.setMenuName("商品分类");
menu5.setId(5);
menu5.setPid(2);
MenuRespVO menu6 = new MenuRespVO();
menu6.setMenuName("文章二级分类");
menu6.setId(6);
menu6.setPid(3);
List<MenuRespVO> list = new ArrayList<>();
list.add(menu1);
list.add(menu2);
list.add(menu3);
list.add(menu4);
list.add(menu5);
list.add(menu6);
List<MenuRespVO> result = new ArrayList<>();
for (MenuRespVO respVO : list) {
if (respVO.getPid().equals(0)) {
findChilds(respVO, list);
result.add(respVO);
}
}
System.out.println(result);
List<MenuRespVO> finalResult = dealData(list, 0);
System.out.println(finalResult);
}
private void findChilds(MenuRespVO respVO, List<MenuRespVO> list) {
List<MenuRespVO> childList = new ArrayList<>();
for (MenuRespVO item : list) {
if (respVO.getId().equals(item.getPid())) {
childList.add(item);
}
}
if (childList.size() == 0) {
return;
}
respVO.setChildList(childList);
for (MenuRespVO childs : childList) {
findChilds(childs, list);
}
}
private List<MenuRespVO> dealData(List<MenuRespVO> list, int pid) {
List<MenuRespVO> result = new ArrayList<>();
list.forEach(item -> {
if (item.getPid().equals(pid)) {
List<MenuRespVO> child = dealData(list, item.getId());
if (child.size() != 0) {
item.setChildList(child);
}
result.add(item);
}
});
return result;
}
}
参考链接
|