Home > php教程 > php手册 > body text

构建网站:用递归函数写个论坛

WBOY
Release: 2016-06-13 11:20:57
Original
925 people have browsed it

论坛的实现方法较为复杂,只要把它分析一下,问题就迎刃而解了,先看看论坛的实现,有人发贴,然后有人跟贴,这个关系形成了一种父子的关联关系,一般写个实用论坛,只要解决了这个子父关系,论坛即已成形.
来看看完成论坛的方法,首先得用数据库来记载这种子父的关系,一般的方法是用无重复的 id 号来完成的,记载父贴的 id 号字段一般用 "parentid" 来记载,子贴存储时记载父贴的 id 号,而父贴的 parentid 则一率为 0,看看数据库的记载形式:
父1:id:1 | parentid:0
子1:id:2 | parentid:1
子子1:id:3 | parentid:2
父2:id:4 | parentid:0
子2:id:5 | parentid:4
子2:id:6 | parentid:4
......
如此数据库记载的子父关系已确立,接着来分析 php 是如何来实现这种父子关系的确立并加入到数据库的,首先用户想发言时,他的贴为一个父贴,因此 php 可将 parentid 设置为 0,当有用户跟贴时,php 将该用户所跟的父贴的 id 号附值给 parentid,这样 php 就完成了,子父关系的确立.
实现了子父关系的确立和存储,接下来就是把这种关系显示出来,这儿就需要用到递归函数来实现了,看下面的代码:
.....
$result=mysql_query("select * from table where parentid=0");
$num=mysql_numrows($result);
if (!empty($num)) {
for ($i=0;$i$parentid=mysql_result($result,$i,"id");
function showchild($parentid) {
//加入 ul 控制层进
$result=mysql_query("select * from table where parentid=$parentid");
$numb=mysql_numrows($result);
if (!empty($numb)) {
for ($i=0;$i....
$parentid=mysql_result($result,$i,"id");
....
showchild($parentid);
}
....
....
}
....
....
}
showchild($parentid);
....
....
}
....
....
}
上面这段代码就是利用递归函数来实现论坛的方法,当然这个论坛是极其原始的,在不同部分加上功能代码,就能够使这个论坛逐渐强大起来,有兴趣的读者不妨自己动手试试.


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!