我有时会在数组和结构之间感到有点困惑。但是,我想我现在理解正确,我的数据在技术上是一系列结构(如果我错了,请纠正我):
<cfset Contacts = [
{
ID = "1",
CompanyName = "Company One",
FirstName = "Elliott",
LastName = "Smith",
...etc...
},
{
ID = "2",
CompanyName = "Company Two",
FirstName = "Matthew",
LastName = "Ryan",
...etc...
}
]>
我想通过ID(例如2)搜索此数据,并返回该结构的其余数据(CompanyName,FirstName,LastName等)。
我该怎么做? (如果我的数据不是可搜索的格式,请告诉我如何更改它,以便它。)
谢谢!
答案 0 :(得分:3)
<cfscript>
// array of structs version
contacts = [{
ID = "1",
CompanyName = "Company One",
FirstName = "Elliott",
LastName = "Smith"
},{
ID = "2",
CompanyName = "Company Two",
FirstName = "Matthew",
LastName = "Ryan"
}];
for(i=1; i <= arrayLen(contacts); i++) {
if (contacts[i]['id'] EQ '2') {
writeoutput(contacts[i]['CompanyName'] & '<br />');
writeoutput(contacts[i]['FirstName'] & '<br />');
writeoutput(contacts[i]['LastName'] & '<br />');
break;
}
}
</cfscript>
更新:
这是使用结构体结构的另一个版本:
<cfscript>
contact1 = {
CompanyName = "Company One",
FirstName = "Elliott",
LastName = "Smith"
};
contact2 = {
CompanyName = "Company Two",
FirstName = "Matthew",
LastName = "Ryan"
};
contacts = {
1=contact1,
2=contact2
};
contact_struct=structfind(contacts,'2');
outstr = '';
outstr = outstr & contact_struct['CompanyName'] & '<br />';
outstr = outstr & contact_struct['FirstName'] & '<br />';
outstr = outstr & contact_struct['LastName'] & '<br />';
writeoutput(outstr);
</cfscript>