PHP无限级分类之下拉列表式分类(下)
<?php
include ("conn.php");
function getList($pid=0,&$result=array(),$space=0){
$space=$space+2;
$sql="SELECT*FROM deepcate WHERE pid = $pid";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)){
$row['catename']=str_repeat(' ',$space).'|--|'.$row['catename'];
$result[]=$row;
getList($row['id'],$result,$space);
}
return $result;
}
$rs=getList();
echo"<select name='cate'>";
foreach ($rs as $key=>$val){
echo "<option>{$val['catename']}</option>";
}
echo'</<select>'
?>
对获得的数据进行美化得到上图样式,这就是无限级分类。
为了以后调用方便,我们把递归函数进行封装。
<?php
include ("conn.php");
function getList($pid=0,&$result=array(),$space=0){
$space=$space+2;
$sql="SELECT*FROM deepcate WHERE pid = $pid";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)){
$row['catename']=str_repeat(' ',$space).'|--|'.$row['catename'];
$result[]=$row;
getList($row['id'],$result,$space);
}
return $result;
}
$rs=getList();
function displayCate($pid=0,$selected=1){
$rs=getList($pid);
$str='';
$str.="<select name='cate'>";
foreach ($rs as $key=>$val){
$selectedstr='';
if ($val['id'] == $selected){
$selectedstr="selected";
}
$str.="<option{$selectedstr}>{$val['catename']}</option>";
}
return $str.='</select>';
}
echo displayCate(0,2);
?>这样我们的无限级分类列表样式就完成了。

phpcn_u2966
这个函数getList($pid=0,&$result=array(),$space=0),在$result前加‘&’符号是什么意思?没加这个符号只显示父类的。
8年前 添加回复 0