1

我正在尝试从邻接树模型(id,parent_id)中的 MySQL 数据库中计算/创建或生成 PHP 中的目录。到目前为止,这是我在回显输出时所取得的成就。

1. Category 1
   1 Subcategory 1
   2 Subcategory 2
   3 Subcategory 3
2.  Category 2
   1. Subcategory 1
      1. Subcategory Subcategory 1
      2. Subcategory Subcategory 2
   2 Subcategory 2
      1 Subcategory 1
      2 Subcategory 2

我非常接近,但我想要的输出是:

1. Category 1
    1.1 Subcategory 1
    1.2 Subcategory 2
    1.3 Subcategory 3
2.  Category 2
   2.1. Subcategory 1
      2.1.1. Subcategory Subcategory 1
      2.1.2. Subcategory Subcategory 2
   2.2 Subcategory 2
      2.2.1 Subcategory 1
      2.2.2 Subcategory 2

换句话说,我想在多级层次结构中使用目录格式,如下所示:Chapter.Subchapter.Subchapter.Subchapter TITLE。

我尝试过使用一个递归数组来保留当前索引并连接到前一个索引,但它最终会在每个项目之前添加一个奇怪的长数字,例如,

0.11。2 ..11.2.3.4.5.6。7 ..11..11.2.3.4.5。6台电脑,

相反,它应该只是:

2.7.6 计算机。

(其他数字为其他项目的编号)

这是我一直在处理的代码

renumber(0,0,1,0);

function renumber($parent_id,$level=0,$counter=1) {

    // Counter level keeps track of the current index number
    $counterlevel[$level]=$counter;

    $query = "SELECT defaultTitle, id, pid FROM defaultChapters  WHERE  pid=".$parent_id;

    $res = mysql_query($query) or die(mysql_error());

    // Exit if there are no tree leafs
    if(mysql_num_rows($res) == 0) {return;}

        while (list ($title, $id) = mysql_fetch_row($res))
    {   

        $leveltext[$level][$counterlevel[$level]] = $section.".".$counterlevel[$level];


        echo str_repeat("......",$level)." ".$counterlevel[$level]." ".$section." ".$title."<BR>";
        // Increase the counter of the current level    
        $counterlevel[$level]++;


        // Initialize the level counter                     
        if(!$counterlevel[$level+1]) {

        $counterlevel[$level+1] = 1;
         }

        // Start the function again to find children
        renumber($id,$level+1,$counterlevel[$level+1]);

    } // End While



}

我浏览了所有技术支持论坛,包括这个论坛,似乎没有人为此发布过算法,只是在任何地方都找不到此示例代码。有数百个教程和代码可以从 mysql 数据库中获取 php 中的层次结构树,而无需编号,但没有关于在 php 中计算层次目录的内容。

是否也可以使用 SQL 查询来做到这一点?

4

1 回答 1

0

我会稍微重构它并将编号传递给当前调用:

function renumber($parent_id = 0, $level = 0, $prefix = '')
{
    // we don't need pid in the results
    $query = "SELECT defaultTitle, id
        FROM defaultChapters 
        WHERE pid=$parent_id";

    $res = mysql_query($query) or die(mysql_error());

    // Exit if there are no tree leafs
    if (mysql_num_rows($res) == 0) {
        return;
    }

    // start numbering at 1
    $nr = 1;
    while (list($title, $id) = mysql_fetch_row($res)) {
        // dropped section, not sure where it was used
        echo str_repeat("......", $level) . " $prefix.$nr $title<BR>";

        // Start the function again to find children
        renumber($id, $level + 1, strlen($prefix) ? "$prefix.$nr." : "$nr.");
        // advance list numbering
        ++$nr;
    }
}

renumber();
于 2012-10-01T04:01:44.067 回答