如何在PHP中执行这种类型的增量?
我正在使用以下类别脚本:如何在PHP中执行这种类型的增量?,php,mysql,Php,Mysql,我正在使用以下类别脚本: <?php include("connect.php"); $nav_query = mysql_query("SELECT * FROM `categories` ORDER BY `id`"); $tree = ""; $depth = 1; $top_level_on = 1; $exclude = array(); array_push($exclude, 0); while ($nav_row = mysql_fetch_array($nav_qu
<?php
include("connect.php");
$nav_query = mysql_query("SELECT * FROM `categories` ORDER BY `id`");
$tree = "";
$depth = 1;
$top_level_on = 1;
$exclude = array();
array_push($exclude, 0);
while ($nav_row = mysql_fetch_array($nav_query)) {
$goOn = 1;
for ($x = 0; $x < count($exclude); $x++) {
if ($exclude[$x] == $nav_row['id']) {
$goOn = 0;
break;
}
}
if ($goOn == 1) {
$tree .= $nav_row['name'] . "<br>";
array_push($exclude, $nav_row['id']);
if ($nav_row['id'] < 6) {
$top_level_on = $nav_row['id'];
}
$tree .= build_child($nav_row['id']);
}
}
function build_child($oldID) {
global $exclude, $depth;
$child_query = mysql_query("SELECT * FROM `categories` WHERE parent_id=" . $oldID);
while ($child = mysql_fetch_array($child_query)) {
if ($child['id'] != $child['parent_id']) {
for ($c=0; $c < $depth; $c++) {
$tempTree .= " ";
}
$tempTree .= "- " . $child['name'] . "<br>";
$depth++;
$tempTree .= build_child($child['id']);
$depth--;
array_push($exclude, $child['id']);
}
}
return $tempTree;
}
echo $tree;
?>
该脚本允许无限的类别深度,但有一个主要缺点。它在前端显示类别导航,如下所示:
Cats
- Siamese Cats
- Lilac Point Siamese Cats
Dogs
如何使其显示为这样:
Cats
- Siamese Cats
- Lilac Point Siamese Cats
Dogs
因此,对于每一个额外的类别深度,可以在类别文本的开始缩进处添加另一个空格。因为您已经在跟踪深度,所以请使用它。例如
$indent = '';
for($i = 0; $i < $depth; $i++) {
$indent .= " ";
}
$tempTree .= $indent . "- " . $child['name'] . "<br>";
$indent='';
对于($i=0;$i<$depth;$i++){
$indent.=“”;
}
$TENTREE.=$indent。"- " . $子项['name']。“
”;
要使它看起来像您想要的那样,您可能必须使用0
初始化$depth
还要注意的是,在嵌套的
for
循环中执行SQL查询并不是最好的方法。如果可能,尽量减少查询数量
例如,您可以使用类和,一次获取所有条目,然后使用对象和数组构建树结构。通过一些相当简洁的查询,您可以让SQL完成大部分工作:
$indent = '';
for($i = 0; $i < $depth; $i++) {
$indent .= " ";
}
$tempTree .= $indent . "- " . $child['name'] . "<br>";