在结构数组中搜索特定键值并返回结构

时间:2014-02-26 19:21:15

标签: coldfusion

我有时会在数组和结构之间感到有点困惑。但是,我想我现在理解正确,我的数据在技术上是一系列结构(如果我错了,请纠正我):

<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等)。

我该怎么做? (如果我的数据不是可搜索的格式,请告诉我如何更改它,以便它。)

谢谢!

1 个答案:

答案 0 :(得分:3)

@Leigh的建议很好。因为此时你已经拥有了内存中的数据,即使它非常大,也会很快地循环一个数组。我喜欢使用CFScript来完成这类任务。以下是使用您提供的部分数据的工作示例:

<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>