小编典典

更加高效的层次体系

mysql

我正在尝试编写一个层次结构检测脚本,我已经编写了该脚本,但是只能下降4级。有没有一种方法可以将其压缩为几行,并且可以使用无数个关卡?

这个脚本基本上是相同的代码复制并粘贴4次

<?php
function listCategories($name, $disable_status = 0, $show_nums = 0) {
    echo "<select name='".$name."'>";
    $result = mysql_query("SELECT * FROM categories") or die(mysql_error());
    while($row = mysql_fetch_array($result)) {
        if($row['parent_id']==0) {
            $result2 = mysql_query("SELECT * FROM categories WHERE parent_id=".$row['id']) or die(mysql_error());
            echo "<option value='".$row['id']."'";

            if($disable_status==1&&isParent($row['id'])){
                echo " disabled='disabled'";
            }
            echo ">".$row['name']."</option>";

            while($row2 = mysql_fetch_array($result2)) {
                $result3 = mysql_query("SELECT * FROM categories WHERE parent_id=".$row2['id']) or die(mysql_error());
                echo "<option value='".$row2['id']."'";
                if($disable_status==1&&isParent($row2['id'])){
                    echo " disabled='disabled'";
                }
                echo ">- ".$row2['name']."</option>";

                while($row3 = mysql_fetch_array($result3)) {
                    $result4 = mysql_query("SELECT * FROM categories WHERE parent_id=".$row3['id']) or die(mysql_error());
                    echo "<option value='".$row3['id']."'";
                    if($disable_status==1&&isParent($row3['id'])){
                        echo " disabled='disabled'";
                    }
                    echo ">-- ".$row3['name']."</option>";

                    while($row4 = mysql_fetch_array($result4)) {
                        echo "<option value='".$row4['id']."'>[".$row4['id']."] --- ".$row4['name']."</option>";
                    }
                }
            }
        }
    }
    echo "</select>";
}

function isParent($cat_ID) {
    $result = mysql_query("SELECT * FROM categories WHERE parent_id=".$cat_ID) or die(mysql_error());
    if(mysql_num_rows($result)==0) {
        return FALSE;
    } else {
        return TRUE;
    }
}

我的表结构categories

id, name, parent_id

如果类别没有父类别,parent_id则将为0,否则将为id其父类别的。

感谢所有帮助。


阅读 241

收藏
2020-05-17

共1个答案

小编典典

我想应该遵循以下原则(未经测试,必须适应您的需求):

$q = mysql_query("SELECT id, parent_id, name FROM categories");
while ($r = mysql_fetch_row($q)) {
  $names[$r[0]] = $r[2];
  $children[$r[0]][] = $r[1];
}

function render_select($root=0, $level=-1) {
  global $names, $children;
  if ($root != 0)
    echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
  foreach ($children[$root] as $child)
    render_select($child, $level+1);
}

echo '<select>';
render_select();
echo '</select>';

一种更有趣的方法是使用SQL存储过程,但在这种情况下可能会过分地…

2020-05-17