我有一个foreach,我想比较两个数组中的一些字符串
变量$count_land 的输出
Array
(
["US"] => 186
["DE"] => 44
["BR"] => 15
["FR"] => 3
["other"] => 7
)
其他阵列:
$all_lands_array = ["CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT"];
我需要的是$all_lands_array中具有与$count_land数组相同字母的每个键,并将它们保存在另一个变量中
这意味着我需要获得US、DE、BR、FR和其他,并将它们保存在一个新的变量中
我希望你能理解我的需求:)
这是我的循环,但找不到任何匹配项。。但为什么呢?
foreach($all_lands_array as $lands){
if($lands == $count_land)
return "match";
else
return "no match!";
}
因为您只需循环一个数组,然后对照整个另一个数组检查值。
检查国家代码:
$count_land = array
(
"US" => 186,
"DE" => 44,
"BR" => 15,
"FR" => 3,
"other" => 7
);
$all_lands_array = array("CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT");
$matches = array();
foreach($count_land as $key => $val){
if(in_array($key, $all_lands_array)){
$matches[$key] = $val; // add matches to array;
}else{
// do nothing
}
}
print_r($matches);die;
返回:
阵列([US]=>186[DE]=>44[BR]=>15[其他]=>7)
您必须将变量中的国家/地区保存为数组,并使用in_array检查元素是否在该数组中:
$found = array();
$countries = array_keys($count_land); //stores: US,DE..etc
foreach($all_lands_array as $country){
if(in_array($country, $countries)){ //if a country name is found in $countries array,
//OPTIONALLY: exclude 'other'
//if(in_array($country, $countries) && $country !='other')
$found[] = $country; //store them in the $found variable
}
}
测试
$count_land = array('US'=>1,'DE'=>1,'BR'=>1,'FR'=>1,'other'=>1);
$all_lands_array = ["CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT"];
var_dump($found);
array(4) {
[0]=>
string(2) "DE"
[1]=>
string(2) "US"
[2]=>
string(2) "BR"
[3]=>
string(5) "other"
}