【问题标题】:foreach doesnt do loops for my search [duplicate]foreach 不为我的搜索执行循环[重复]
【发布时间】:2016-01-05 15:17:29
【问题描述】:

我有一个 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 数组的相同字母并将它们保存在另一个变量中

这意味着我需要获取美国、德国、巴西、法国和其他并将它们保存在一个新变量中

我希望你明白我需要什么:)

这是我的循环,但它没有找到任何匹配项.. 但是为什么呢?

foreach($all_lands_array as $lands){
    if($lands == $count_land)
        return "match";
    else
        return "no match!";
    }

【问题讨论】:

  • 您正在将字符串与数组进行比较
  • 只需在键中使用in_array() 进行搜索,您将获得:array_keys($count_land)

标签: php arrays


【解决方案1】:

因为您只需遍历一个数组,然后对照整个另一个数组检查该值。

检查国家代码:

$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 [other] => 7)

【讨论】:

  • 我仍然没有得到任何匹配.. 我的意思是,至少 5 个土地应该匹配.. 但我仍然没有得到任何结果
  • 因为退货。返回存在循环,我已经更新了我的答案以捕捉匹配项。
  • 这只是给了我一个未定义的变量匹配:o
  • 更新了我的答案,请查收。
  • 它仍然给我一个 : undefined variable $matches :O
【解决方案2】:

您必须将变量中的国家/地区保存为数组,并使用 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"
}

【讨论】:

  • 我认为这是正确的方法,但它仍然只是给我:不匹配..我仍然需要一个线索如何将输出保存在另一个变量中
  • 好吧..这有点用,但它只找到了一个匹配..它在输出中给了我“其他”,但应该至少还有 4 个:o
  • 添加了你的变量,我发现所有 3 + 'other'
  • 我只是不知道为什么,但我只是得到一个空数组
  • 你身边一定有小写和大写之类的东西,对于给定数据的问题,这就是答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 2021-02-13
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多