php

一个菜单分类的算法(非递归)

直接上代码

// 菜单树算法(非递归)
function list2tree($list) {
	$tree = [];
	foreach ($list as $v) {
		$tree[$v['id']] = $v;
		$tree[$v['id']]['sub'] = []; //子类
	}
	foreach ($tree as $k=>$v) {
		if ($v['pid']) {
			$tree[$v['pid']]['sub'][] = &$tree[$k];
		}
	}
	foreach ($tree as $k=>$v) {
		if ($v['pid']) {
			unset($tree[$k]);
		}
	}
	return $tree;
}