您好我的php文件中有一个关联数组,我将其作为JSON对象传递给我的js文件。我想循环遍历数组并使用匹配的键找到数组中的项。这就是我到目前为止所做的:
PHP:
<?php
$countries = array(
"United Kingdom"=>"pounds",
"United States"=>"dollars",
"France"=>"euros",
"Germany"=>"euros",
);
echo json_encode($countries);
?>
JS:
var location = "United States";
$.get("location.php", function(data){
var locationArray = JSON.parse(data);
});
我想浏览数组并找到与位置变量匹配的项目(&#34;美国&#34;)。这应该返回"dollars"
。
答案 0 :(得分:0)
你可以这样做:
var return_value = '';
var location_name = "United States";
for(var key in locationArray)
{
if(key == location_name)
{
return_value = key;
}
}
// You can use return_value from here in your code further....
答案 1 :(得分:0)
此处您可以获取unites states
数据
$.get("location.php", function(data){
var locationArray = JSON.parse(data);
console.log(locationArray['United States']);
});
答案 2 :(得分:0)
您也可以使用此代码获取它:
for (var key in locationArray) {
if (key == 'United States') {
var currency = locationArray[key];
}
}