2011-05-06 168 views
0

我有下面的格式返回行的查詢:構建動態分層結構

ID  NAME               PARENTID 
1  Top level.              0 
7  Second level1.             1 
10 Third Level under Second Level1.        7 
22 Second Level2.             1 
23 Third Level1 under Second Level2.        22 
24  Third level2 under Second Level2.        22 

我想要做的就是動態地構建一個結構。上述數據需要按照以下層次結構進行組織:

Top Level. 
    Second Level1. 
       Third Level under Second Level1. 
    Second Level2. 
       Third Level under Second Level2. 
       Third Level under Second Level2. 

數據可能是任何東西,對層次結構的深度沒有限制。我正在尋找一種編程方式將這些數據組織到一個結構中,而不管查詢返回的是什麼。我在ColdFusion中寫這個,所以如果你有CF的例子,那將是很好的,但僞代碼會很好。謝謝您的幫助。

回答

0

調用此函數併爲0傳遞parentID和q_query的查詢結果。

<cffunction name="generateArray" returntype="Array"> 
    <cfargument name="parentID" type="Numeric" required="yes" default=0 > 
    <cfargument name="q_query" type="query" required="yes"> 

    <cfquery name="getChildren" dbtype="query"> 
     SELECT * 
     FROM q_query 
     WHERE parentid = <cfqueryparam value="#parentID#" cfsqltype="CF_SQL_INTEGER"> 
     ORDER BY sequence; 
    </cfquery> 

    <cfset treeArray = ArrayNew(1)> 
    <cfloop query="getChildren"> 
      <cfquery name="checkForChildren" dbtype="query"> 
       SELECT * 
       FROM q_query 
       WHERE parentid = <cfqueryparam value="#getChildren.id#" cfsqltype="CF_SQL_INTEGER"> 
      </cfquery> 

      <cfset treeStruct = structNew()> 
      <cfset treeStruct["id"] = getChildren.id> 
      <cfset treeStruct["name"] = getChildren.name> 
      <cfset treeStruct["children"] = ArrayNew(1)> 
      <cfif checkForChildren.recordcount gt 0> 
       <cfinvoke component="cfcs.thisCfc" method="GenerateArray" parentID="#Val(getChildren.ID)#" q_query="#q_query#" returnvariable="children"> 
       <cfset treeStruct["children"] = children> 
      </cfif> 
      <cfset temp = ArrayAppend(treeArray, treeStruct)> 
    </cfloop> 
    <cfreturn treeArray> 
</cffunction>