php中构建树状图
/** * 指定根层级的树状图 * @param array $list 初始数组 * @param int $root 最上级一条数据的id * @param string $pk 每一条数据的id * @param string $pid 上下级关系的pid * @param string $child 自定义下级关系的字段 * @return array $tree 树状图数组 */ function generateTree($list, $root = 0, $pk = 'id', $pid = 'pid', $child = '_child') { $tree = array(); $packData = array(); foreach ($list as $data) { $packData[$data[$pk]] = $data; } foreach ($packData as $key => $val) { if ($val[$pid] == $root) { //代表跟节点, 重点一 $tree[] = &$packData[$key]; } else { //找到其父类,重点二 $packData[$val[$pid]][$child][] = &$packData[$key]; } } return $tree; }
获取无限极的层级,
public static function getTree($data, $pid, $level = 0) { $list = array(); foreach ($data as $k => $v) { if ($v['parent_id'] == $pid) { $v['level'] = $level; $v['name'] ='| — —' . str_repeat('| — —', $level) . $v['name'];// 这里可以加个层级次数 //一个层级增加一维数组
// $v['children'] = self::getTree($data, $v['id'], $level + 1); $list[] = $v;
//构建二级数组
$list = array_merge(self::getTree($data, $v['id'], $level + 1), $list);
} } return $list; }