表结构:
实现代码:
public function findChild(&$data, $parent_id = 0) {
$rootList = array();
foreach ($data as $key => $val) {
if ($val['parent_id'] == $parent_id) {
$rootList[] = $val;
unset($data[$key]);
}
}
return $rootList;
}
public function getTree(&$data, $parent_id = 0) {
$Model = M('tiku_point');
$childs = $this->findChild($data, $parent_id);
if (empty($childs)) {
return null;
}
foreach ($childs as $key => $val) {
$result = $Model->where("parent_id=".$val['id'])->find();
if ($result) {
$treeList = $this->getTree($data, $val['id']);
if ($treeList !== null) {
$childs[$key]['childs'] = $treeList;
}
}
}
return $childs;
}
//调用方法
public function getAllPoints(){
$Model = M('tiku_point');
$child_data = $Model->where("course_id=3")->select(); //获取所有知识点
$data = $this->getTree($child_data,$pid = 0);
var_dump($data);exit;
}
本文介绍了一种通过递归方式构建树状结构数据的方法。利用PHP实现了一个具体案例,从数据库中获取所有知识点数据,并将其组织成树形结构,便于前端展示。此方法适用于需要将层级关系的数据进行可视化展示的场景。
134

被折叠的 条评论
为什么被折叠?



