PHP development classification technology drop-down menu classification (3)
We customize a function displayCate to add the
<selsct> style to the looped getList to output the drop-down menu, similar to the following:
| -- Clothing
|-- Men's clothing
|-- Women's clothing
|-- Food
## |-- Staple food
|-- Rice
|-- Non-staple food
Output the classification style through the foreach loop, and the drop-down menu defaults to the first-level classification.<?php 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['title']}</option>"; } return $str.="</select>"; } echo displayCate(0,3); ?>Complete implementation of drop-down menu effect code:
<?php header("content-type:text/html;charset=utf8"); $link = mysqli_connect('localhost','username','password','test'); mysqli_set_charset($link, "utf8"); if (!$link) { die("连接失败:".mysqli_connect_error()); } function getList($pid=0,&$result=array(),$space=0){ global $link; $space=$space+2; $sql="select * from class where pid = $pid"; $res = mysqli_query($link,$sql); while ($row = mysqli_fetch_assoc($res)){ $row['title']=str_repeat(' ',$space).'|-- '.$row['title']; $result[]=$row; getList($row['id'],$result,$space); } return $result; } $rs=getList(); print_r($rs); 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['title']}</option>"; } return $str.="</select>"; } echo displayCate(0,3); ?>