初学递归,接触无限分类,小小的尝试

今日学习的是无限循环,这与递归有关。其实我本身还不是彻底熟悉和上手,还须要琢磨琢磨。php

初步学习递归,算是无限分类的一个小练习。 ** 表:cate id int auto 自动递增 pid int 0为最大的分类 catename varchar 分类名称 **html

读取数据库的cate表分类以下: //分类练习 include '../include.php';mysql

function getList($pid=0,&$result=array(),$spac=0)
{
	$spac = $spac + 4;
	$sql = "SELECT * FROM cate where pid='$pid' ";
	$query = mysql_query($sql);

	//获取数组,传入$result
	while($row = mysql_fetch_assoc($query))
	{
		$row['catename'] = str_repeat(' ', $spac).'|--'.$row['catename'];
		$result[] = $row;
		//递归就是调用本身自己
		getList($row['id'],$result,$spac);
	}
	return $result;
}

//封装
function display($pid=0)
{
	$rs = getList($pid);
	$str = '<select name="cate">';
	foreach ($rs as $key => $value) {
		$str .="<option>{$value['catename']}</option>";
	}
	return $str .="</select>";
}
echo display();

运行效果: 在此输入图片描述 在此输入图片描述 输入分类:sql

<html> <meta http-equiv="content-type" content="text/html" charset="utf8"> <head> <title>添加分类</title> </head> <body> <h1 align="center">添加分类</h1> <hr> <form method="post" action="cate.php"> <table width="600" align="center" border="0" cellpadding="0" cellspacing="1" > <tr> <td width="80">请输入分类</td> <td width="40"><input type="text" name="catename" size="20"></td> <td width="50">分类id</td> <td width="30"><input type="text" name="pid"></td> <td><input type="submit" name="sub" value="提交"></td> </tr>数据库

</table>
<!-- 方便本身查看作的实时表查看分类 -->
<table align="center" border="1">
	<h1 align="center">现有信息表</h1>
<hr>
<?php 
while($res = mysql_fetch_array($query))
	{
?>
	<tr>
		<td>id:</td>
		<td><?php echo $res['id']; ?></td>
		<td>分类名称</td>
		<td><?php echo $res['catename']; ?></td>
		<td>pid:</td>
		<td><?php echo $res['pid']; ?></td>
		<br>
	</tr>

<?php } echo '</table> </form> </body> </html>'; // 实时表到这里结束 //填写分类名称catename,pid if(isset($_POST['sub'])){ $catename = $_POST['catename']; $pid = $_POST['pid']; $table = 'cate'; if(empty($catename)) { echo "分类名不能为空哦"; }else{ cate($table,$catename,$pid);//调用 sql.func.php中的cate分类函数 } } ?>数组

运行效果: 在此输入图片描述函数

相关文章
相关标签/搜索