2011-09-02 43 views
0

對不起大家回來了,我的遞歸數組能正常工作,但我無法得到「佈局」正確的我以後是使用<ul><li>這樣的「適當」樹形結構,所以你最終會像這樣:遞歸數組正確的顯示方法

  • 項目
    • 兒童
      • 孩子的兒童
        • 等...

我的功能看起來是這樣的 - 而功能工作的 「佈局」 不建議請。

function recursive_array($results,$tbl) { 
global $DBH; 
$tbl = $tbl; 
if (count($results)) { 
    foreach($results as $res) { 
     if($res->ParentID == 0) { 
     echo '<ul class="recursive">'; 
     echo '<li>';  
     echo $res->Name; 
     echo $res->Description; 
     echo $res->date_added; 
     echo '<ul>'; 
     } 

     if($res->ParentID != 0) { 
     echo '<li>'; 
      echo $res->Name; 
      echo $res->Description; 
      echo $res->date_added; 
     echo '</li>'; 
     } 


     $STH = $DBH->query("SELECT * FROM ".$tbl." WHERE ParentID = '".$res->ID."'"); 
     $fquerycount = $STH->rowCount(); 
     $STH->setFetchMode(PDO::FETCH_OBJ); 
     recursive_array($STH,$tbl); 
     if($res->ParentID == 0) { 
     echo '</ul></li></ul>'; 
     }  
    } 
} 
} 

回答

1

我真的不是遞歸SQL的粉絲。我用它,它的工作原理,但它總是讓我感到...... yeck ...

如何改爲:創建一個topicID(某種選擇器,其中將包括所有的項目,你會最終喜歡有輸出),並根據它進行選擇,按parentID排序。

SELECT * FROM $tbl WHERE topicID = 1 ORDER BY parentID; 

然後,組織這樣的:

$output = array(); 
$currentParent = -1; 
while($row = $stmt->fetch(PDO::FETCH_OBJ)) 
{ 
    if($currentParent != $row->ParentID) 
    { 
     $currentParent = $row->ParentID; 
     $output[ $currentParent ] = array(); 
    } 
    $output[ $currentParent ][] = $row; 
} 

function outputLists(array $current, array $output) 
{ 
    echo '<ul>'; 
    foreach($current as $res) 
    { 
     echo '<li>'; 
     echo $res->Name; 
     echo $res->Description; 
     echo $res->date_added; 
     // if it is set, clearly we have a node to traverse 
     if(isset($output[ $res->ID ])) 
      // seed the next call to the function with the new 
      // node value (found in output) and it will create 
      // the appropriate ul and li tags 
      outputLists($output[ $res->ID ], $output); 
     echo '</li>'; 
    } 
    echo '</ul>'; 
} 
// start with the group with parentID = 0 
outputLists($output[ 0 ], $output); 

所以,而不是遞歸SQL,你必須從數據庫PHP創建樹狀結構中的一個輸出。

+0

完美!我同意遞歸數組,但是...有時是有用的 –