首页 > 解决方案 > ColdFusion中结构数组的分组和排序结果

问题描述

我在 ColdFusion 中有一系列结构。我想按一个元素对结果进行分组,并根据结构的其他几个属性对其进行排序。实现这一目标的最有效和最现代的方法是什么?如果需要,我可以更改查询的排序顺序。

例如,现在我首先按标题对它进行排序,然后按它进行分组,将当前循环标题与前一个标题进行比较,如果它发生了变化,我会看到新的。

myArray[1]
struct
Title = Heading 1
Description = lorem ipsum
Field 2 = this has to be second #1
Field 1 = this has to be first #1
Field 3 = this has to be third #1

myArray[2]
struct
Title = Heading 1
Field 3 = this has to be third #2
Field 1 = this has to be first #2
Description = dolor sit amet
Field 2 = this has to be second #2


myArray[3]
struct
Title = Heading 2
Description = onsectetur adipiscing elit.
Field 1 = this has to be first #3
Field 2 = this has to be second #3
Field 3 = this has to be third #3

myArray[3]
struct
Title = Heading 2
Description = Nullam ultrices
Field 1 = this has to be first #4
Field 2 = this has to be second #4
Field 3 = this has to be third #4

必须对结果进行分组和排序,如下所示:

Heading 1 = show ONE time because it is the title that I want to group the results
dolor sit amet  = sorted descriptions (this can be done from the SQL Query)
lorem ipsum  = sorted descriptions (this can be done from the SQL Query)
this has to be first #1 = sorted Fields (this can be done from the SQL Query)
this has to be second #1
this has to be third #1
this has to be first #2
this has to be second #2
this has to be third #2

--
Heading 2
onsectetur adipiscing elit.
Nullam ultrices
this has to be first #3 
this has to be second #3
this has to be third #3
this has to be first #4
this has to be second #4
this has to be third #4
```

  <cfif myArray[i].Title neq local.prevTitle>
    <h2>#Title#/h2>
  </cfif>
  <cfif myArray[i].Title neq local.prevTitle>
   <ul>
  </cfif>
    <li>#Description#</li>
    <li>#Field1#</li>
    <li>#Field2#</li>
    <li>#Field3#</li>
 <cfif i neq arrayLen(myArray) AND myArray[i+1].Title neq myArray[i].Title>
   </ul>
</cfif>
<cfif i eq arrayLen(myArray)>
   </ul>
</cfif>
<cfset prevTitle= myArray[i].Title />

我还需要在分组标题之前和结果组之后添加 HTML 元素。例如,<hr>在开始之前显示新的分组结果。我很少检查数组中是否还有另一个元素,如果它不是最后一个元素,并且标题已更改为显示 HR。像这样的东西:

<cfif i neq arrayLen(myArray) AND myArray[i+1].Title neq myArray[i].Title>
     <hr />
</cfif>

但我在想必须有一种更有效和更现代的方式来做到这一点。所以如果有人有任何建议,我很乐意阅读。

谢谢!

标签: arrayscoldfusionstructuregrouping

解决方案


推荐阅读