我正在尝试在邻接树模型(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查询执行此操作?
答案 0 :(得分: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();