import Foundation
class File: UIViewController {
override func viewDidLoad() {
super.viewDidLoad();
self.title = "递归转换数据"
var images : Array
var department = DepartmentModel(iid: 1, ppid: 1, nname: "a", cchilds: []);
department.id = 1;
department.pid = 0;
department.name = "一级";
department.childs = [];
images.append(department);
var department2 = DepartmentModel(iid: 1, ppid: 1, nname: "a", cchilds: []);
department2.id = 2;
department2.pid = 1;
department2.name = "二级";
department2.childs = [];
images.append(department2);
var department3 = DepartmentModel(iid: 1, ppid: 1, nname: "a", cchilds: []);
department3.id = 3;
department3.pid = 2;
department3.name = "三级";
department3.childs = [];
images.append(department3);
var department21 = DepartmentModel(iid: 1, ppid: 1, nname: "a", cchilds: []);
department21.id = 3;
department21.pid = 1;
department21.name = "二级";
department21.childs = [];
images.append(department21);
let tree = self.buildTree(data: images);
log.info("over");
}
func buildTree(data : Array
var dataArray : Array
var intIdArray : Array
for index in 0..
let dic = data[index] ;
let id = dic.id;
intIdArray.append(id);
}
//迭代遍历
for i in 0..
var dic = data[i] ;
let pid = dic.pid;
if !intIdArray.contains(pid) {
recursionFn(data: data,dddd: dic);
dataArray.append(dic);
}
}
if dataArray.isEmpty {
dataArray = data;
}
return dataArray;
}
//递归
func recursionFn(data : Array
var tempDictionary : Dictionary
var child = getChildList(data: data, dictionary: dddd) ;
dddd.childs = child ;
for index in 0.. var dictionary = child[index] ; if hasChild(data: data, dictionary: dictionary) { recursionFn(data: data, dddd: dictionary); } } } func getChildList(data : Array var tempData : Array for i in 0.. let dic = data[i] ; let pid = dic.pid;//父id if Int(pid) == dictionary.id { tempData.append(dic); } } return tempData; } func hasChild(data : Array let boo = getChildList(data: data, dictionary: dictionary).count > 0 ?true:false; return boo; } } 欢迎分享,转载请注明来源:内存溢出
评论列表(0条)