PHP 無限分類ドロップダウン リスト分類 (パート 2)

<?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('&nbsp;',$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>'
?>

QQ截图20161029103008.png

取得したデータを美化して上記のようなピクチャースタイルを得る、無限分類です。

今後の呼び出しの便宜のために、再帰関数をカプセル化します。

<?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('&nbsp;',$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);
?>

これで無限カテゴリリストスタイルが完成しました。

学び続ける
||
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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);
?>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
图片放大关闭