2012-04-29 4 views
3

나는이 같은 내 사이트에 대한 의견을으로 모니터하고 싶습니다 : 나는 the following article을 읽고중첩 된 주석을 어떻게 구현합니까?

<li>Parent 
    <ul> 
     <li>child one</li> 
     <li>child two 
      <ul> 
       <li>grandchild</li> 
       <li>other grandchild</li> 
      </ul> 
     </li> 
    </ul> 
<li>Another parent with no children</li> 
<li> 

그러나 그것은 <li>를 사용하지 않습니다. 그래서 배열과 같이 전에했던 것처럼 주석을 표시하는 방법이 있습니까? 감사.

$comments = array(
     array('id'=>1, 'parent_id'=>NULL, 'text'=>'Parent'), 
     array('id'=>2, 'parent_id'=>1,  'text'=>'Child'), 
     array('id'=>3, 'parent_id'=>2,  'text'=>'Child Third level'), 
     array('id'=>4, 'parent_id'=>NULL, 'text'=>'Second Parent'), 
     array('id'=>5, 'parent_id'=>4,  'text'=>'Second Child') 
); 
+2

예, 완벽하게 가능합니다. * 트리를 만드는 * 재귀 * 함수를 만들어야합니다. (Google, 그걸 찾아서 ...) – deceze

+0

또한이 트리 구조를 일반 목록으로 펼친 다음 간단한 foreach를 사용하여 출력 할 수도 있습니다 –

+0

[부모 - 자식 관계의 연속을 계층 적 트리?] (http://stackoverflow.com/questions/2915748/how-can-i-convert-a-series-of-parent-child-relationships-into-a-hierarchical-tre) -이 질문을 받았다. 전에 [그리고 대답] (http://stackoverflow.com/a/8285070/367456). 배열 구조를 중첩 된 세트와 같은 다른 구조로 변환하는 것도 유용합니다. – hakre

답변

4

나는 당신의 코멘트 테이블 ID, PARENT_ID, 주석, ...을 가지고 있으며, 내 제안은 다음과 같이 간다 asssume;

당신의 코멘트를 선택하십시오;

$sql = "SELECT *FROM comments ORDER BY id DESC"; 

$rows = mysql_query($sql); 

그리고 다음 단계

는 operations.You 아래에 다음 코드를보고 데모 here 작업 시도 할 수 있습니다 배열입니다; 데모

$rows = your_select_result;//I assumed that you have done these stuffs 
$comments = $row; 
/** 
This is test data, please remove this array while you are 
running own application.Since you will use the data one you get your db 
**/ 
$comments = array(
    1 => array('id' => 1, 'parent_id' => 0, 'childs' => array()), 
    2 => array('id' => 2, 'parent_id' => 0, 'childs' => array()), 
    3 => array('id' => 3, 'parent_id' => 0, 'childs' => array()), 
    5 => array('id' => 5, 'parent_id' => 0, 'childs' => array()), 
    11 => array('id' => 11, 'parent_id' => 0, 'childs' => array()), 
    17 => array('id' => 17, 'parent_id' => 0, 'childs' => array()), 
    23 => array('id' => 23, 'parent_id' => 0, 'childs' => array()), 
    28 => array('id' => 28, 'parent_id' => 0, 'childs' => array()), 
    4 => array('id' => 4, 'parent_id' => 1, 'childs' => array()), 
    6 => array('id' => 6, 'parent_id' => 1, 'childs' => array()), 
    8 => array('id' => 8, 'parent_id' => 2, 'childs' => array()), 
    9 => array('id' => 9, 'parent_id' => 2, 'childs' => array()), 
    7 => array('id' => 7, 'parent_id' => 3, 'childs' => array()), 
    12 => array('id' =>12, 'parent_id' => 7, 'childs' => array()), 
    13 => array('id' => 13, 'parent_id' => 12, 'childs' => array()), 
); 

/** Comment prepare start */ 
foreach ($comments as $k => &$v) { 
    if ($v['parent_id'] != 0) { 
     $comments[$v['parent_id']]['childs'][] =& $v; 
    } 
} 
unset($v); 

foreach ($comments as $k => $v) { 
    if ($v['parent_id'] != 0) { 
     unset($comments[$k]); 
    } 
} 

/** Comment prepare end */ 

//Your indent pattern 
function indent($size) { 
    $string = ""; 
    for ($i = 0; $i < $size; $i++) { 
     $string .= "#"; 
    } 
    echo $string; 
} 


function printComments($comments, $indent = 0) { 
    foreach ($comments as $comment) { 
     echo indent($indent + 1).' I am comment '.$comment['id']."\n"; 
     if (!empty($comment['childs'])) { 
      printComments($comment['childs'], $indent + 1); 
     } 
     } 
} 


printComments($comments); 

구체화 된 경로 기술을 사용하는 경우, BTW here

+0

2 차원 계층 구조에 적합하지만 임의로 중첩 된 항목에 대해서는 전혀 작동하지 않습니다 (여기에서 요구되는 것처럼). – deceze

+0

네, 맞습니다. 나는 코드의 논리를 바꾸지 않고 코드를 업데이트했다. 또한 작업 데모를 추가했다. –

1

참조하십시오, 당신은 더 재귀도 중첩 된 배열 또는 물건을 필요로하지 않습니다.

데이터베이스에서 평범한 선형 출력.

데이터베이스에 path이라는 필드를 만들고 모든 상위 ID를 채우려면 몇 가지 고려해야 할 길이로 채워야합니다. 말은, 예를 들어 트리처럼 보일 수 있습니다

id 1 root path 
    id 3 root 1 path 000000001 
     id 5 root 1 path 000000001000000003 
    id 4 root 1 path 000000001 
id 2 root path 000000002 
    id 6 root 2 path 

그래서, 간단한 이미 정렬 된 목록

0

로 트리를 얻을 것이다 간단한 ORDER BY root DESC, path ASC
하여 테이블을 쿼리이 기능은 parent_id해야합니다 각 코멘트 배열에 id 키가 있어야합니다.

$comments = array(
      array('id'=>1, 'parent_id'=>NULL, 'text'=>'Parent'), 
      array('id'=>2, 'parent_id'=>1, 'text'=>'Child'), 
      array('id'=>3, 'parent_id'=>2, 'text'=>'Child Third level'), 
      array('id'=>4, 'parent_id'=>NULL, 'text'=>'Second Parent'), 
      array('id'=>5, 'parent_id'=>4, 'text'=>'Second Child') 
     ); 

이렇게하면 다차원 배열이 반환됩니다. 하나의 항목에 자식이 없으면 $comment['children']NULL과 같을 것입니다. 그렇지 않으면 자식 배열이 첨부됩니다.

function arrangecomments($comments){ 

    $tree = array(); 

    /* We get all the parent into the tree array */ 
    foreach ($comments as &$node) { 
     /* Note: I've used 0 for top level parent, you can change this to == 'NULL' */ 
     if($node['parent_id']=='0'){ 
      $tree[] = $node; 
      unset($node); 
     } 
    } 

    /* This is the recursive function that does the magic */ 
    /* $k is the position in the array */ 
    function findchildren(&$parent, &$comments, $k=0){ 
     if (isset($comments[$k])){ 
      if($comments[$k]['parent_id']==$parent['id']){ 
       $com = $comments[$k]; 
       findchildren($com, $comments); // We try to find children's children 
       $parent['children'][] = $com; 
      } 
      findchildren($parent, $comments, $k+1); // And move to the next sibling 
     } 
    } 

    /* looping through the parent array, we try to find the children */ 
    foreach ($tree as &$parent) { 
     findchildren($parent, $comments); 
    } 

    return $tree; 

} 

많은 개선이있을 수 있지만 제대로 작동하고 있으며 지금까지 버그를 발견하지 못했습니다. 희망이 도움이됩니다!

관련 문제