2010-06-19 3 views
0

나는이 카테고리 스크립트를 사용하고 있습니다 :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_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; 

?> 

:

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 –

답변

0

이미 깊이를 추적하고 있으므로 사용하십시오. 예 :

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

은 당신이 0$depth를 초기화해야 할 수도 있습니다 당신이 그것을 원하는 방식으로 보이게합니다.


또한 중첩 된 for 루프에서 SQL 쿼리를 실행하는 것이 최선의 방법이 아닙니다. 가능한 경우 쿼리 수를 줄이십시오.

예를 들어 클래스를 사용하고 모든 항목을 한 번에 가져온 다음 개체 및 배열을 사용하여 트리 구조를 작성할 수 있습니다.

관련 문제