根据json数据的机场代码获取机场名称

时间:2014-02-19 09:57:13

标签: javascript json country-codes

在航班预订网站上工作。拥有json文件,其中包含机场代码,城市名称和国家/地区名称。

[{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}]

现在,如果我的iata机场代码与UTK匹配,我想返回该名称。

3 个答案:

答案 0 :(得分:1)

使用filter()Array中找到iata内的对象:

var arr = [{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}];

function findByCode(arr, iata){
    var filtered = arr.filter(function(e){return e.iata = iata});
    return (filtered.length == 1) ? filtered[0]:undefined;
}

console.log(findByCode(arr,"UTK").name);

JS小提琴: http://jsfiddle.net/dE9nP/

答案 1 :(得分:0)

这是基本搜索!您需要遍历数组,并检查每个项目的匹配代码,然后返回结果。这是一个功能:

function findAirport(myArray, iata){
    for(var i = 0; i < myArray.length; i++){
        var item = myArray[i];
        if(item["iata"] === iata){
            return item;
        }
    }
    return null;
}

您可以像这样使用该功能:

var airports = [{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}];
var match = findAirport(airports, "UTK");
if(match){
    console.log("name = " + match.name);
}

只是为了强调我使用简单的for循环优于其他函数,例如filterhere is a performance test将我的答案与使用filter的其他函数进行比较。我知道在大多数实际用例中它没有意义,但我想保留对jsperf链接的引用:)

注意:在编辑问号之前提供了此答案。在发布时,这个问题是要求javascript解决方案

答案 2 :(得分:0)

$string = '[{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"}]';
 $data = json_decode($string);
echo count($data);
for($i=0;$i<count($data);$i++){
if($data[$i]->iata == 'UTK') echo $data[$i]->name;
}

如果文件中的数据而不是$ string,则可以使用file_get_contents;