2010-06-19 45 views
0

我使用這一類的腳本:如何在PHP中執行這種類型的增量?

<?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 .= "&nbsp;"; 
         } 
      $tempTree .= "- " . $child['name'] . "<br>"; 
      $depth++; 
      $tempTree .= build_child($child['id']); 
      $depth--; 
      array_push($exclude, $child['id']); 
     } 
    } 

    return $tempTree; 
} 

echo $tree; 

?> 

它依賴於下面的MySQL數據庫結構:

id | parent_id | name 

1    Cats 
2 1   Siamese Cats 
3 2   Lilac Point Siamese Cats 
4    Dogs 

etc... 

腳本允許無限制的類別深度,但有一個主要的垮臺。它顯示了類別導航到前端像這樣:

Cats 
- Siamese Cats 
- Lilac Point Siamese Cats 
Dogs 

我怎樣才能把它顯示是這樣的:

Cats 
- Siamese Cats 
    - Lilac Point Siamese Cats 
Dogs 

讓每增加品類深度被添加到開始另一個空間類別文本的縮進?

+0

隨着一些相當整潔的查詢,你可以讓你的SQL做大部分的工作:http://dev.mysql.com/tech-resources/articles/hierarchical-data.html – 2010-06-19 17:57:23

回答

0

由於您已經掌握了深度,請充分利用它。例如。

$indent = ''; 
for($i = 0; $i < $depth; $i++) { 
    $indent .= "&nbsp;"; 
} 
$tempTree .= $indent . "- " . $child['name'] . "<br>"; 

,使它看起來你想要它,你可能有0初始化$depth的方式。


另請注意,在嵌套的for循環中執行SQL查詢並不是最好的方法。如果可能,儘量減少查詢次數。

例如,您可以使用類,並立即獲取所有條目,然後用對象和數組構建樹結構。

相關問題