使用struct key对隐式结构的隐式数组进行排序 [英] Sorting an implicit array of implicit structs by struct key
问题描述
根据第一个在这篇博客中的例子,我有一个隐式数组的隐式结构。我的数据实际上很相似,例如:
Based on the first example in this blog post, I have an implicit array of implicit structs. My data is actually pretty similar, e.g.:
<cfset ReportsArray = [
{
Name = "My First Report",
Group = "Group One"
},
{
Name = "My Second Report",
Group = "Group Two"
},
{
Name = "My Third Report"
Group = "Group One"
},
...etc...
]>
我决定以这种格式创建数据,这样我可以稍后将新报告推送到数组在任何组中,或者只需要重新写入一个新的报告列表(如果需要)。我想知道是否可以根据组键在结构中排序这个数组,以便我可以循环通过它们并输出如下:
I decided to create the data in this format so that I can later push a new report to the array in any group, or just rewrite the array with a new list of reports if needed. I'm wondering if it's possible to sort this array based on the "Group" key in the structs so that I can loop through them and output something like this:
第一组
我的第一份报告
我的第三份报告
第二组
我的第二份报告
-
这是否有意义?
推荐答案
也许查询会是正确的工作数据类型吗?使用ColdFusion的着名的查询查询,排序这样的数据是一块蛋糕。
Maybe Query would be the right data type for the right job? with ColdFusion's famous Query of Queries, sorting data like this is a piece of cake.
如果你真的想排序对象数组,而你在CF10 +你是运气。您可以使用ArraySort与回调函数: https://wikidocs.adobe.com/wiki/display/ coldfusionen / ArraySort 。
If you really want to sort an array of objects, and you're in CF10+, you are in luck. You may use ArraySort with callback: https://wikidocs.adobe.com/wiki/display/coldfusionen/ArraySort.
如果你坚持,这里是一个易于阅读的气泡排序,将工作在CF8:
If you insist, here's a easy to read bubble sort that would work in CF8:
<cfscript>
function sortReports(reports)
{
var local = {};
local.sorted = false;
local.reportSize = arrayLen(reports);
while (!local.sorted)
{
local.sorted = true;
for (local.i = 1; local.i < local.reportSize ; local.i = local.i + 1)
{
local.report1 = reports[local.i];
local.report2 = reports[local.i + 1];
if (local.report1.group > local.report2.group)
{
arraySwap(reports, local.i, local.i + 1);
local.sorted = false;
}
}
}
return reports;
}
reportsArray = [
{
Name = "My First Report",
Group = "Group One"
},
{
Name = "My Second Report",
Group = "Group Two"
},
{
Name = "My Third Report",
Group = "Group One"
}
];
</cfscript>
<cfdump var="#sortReports(reportsArray)#">
在这里运行: http://www.trycf.com/scratch-pad/pastebin?id=RuSHgZYq
这篇关于使用struct key对隐式结构的隐式数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!