嵌套的foreach如果不工作 [英] Nested foreach if else not working

查看:159
本文介绍了嵌套的foreach如果不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的foreach循环,通过两个数组使用条件 if - else 。当if语句返回一个值时,else语句还在运行,为什么?

  // $ global_plugins是一个数组
// $ xml_plugins是一个字符串

foreach($ global_plugins as $ key => $ global_plugins){
foreach((array)$ xml_plugins as $ key2 => $ xml_plugins ){

if(($ global_plugins == $ xml_plugins)&&($ plugin_verso [$ key] == $ xml_plugin_version [$ key2])){

回声'完全匹配';

} else {

echo'模糊匹配';




$ b code $ pre

在这个例子中,当 if 返回一个完全匹配时,它不应该返回模糊匹配这是发生了什么事情。

对于1个匹配的值,我得到了echo输出:完全匹配一次和模糊匹配x 10

解决方案

您应该使用 break a $> $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' )$ xml_plugins as $ key2 => $ xml_plugins){

if(($ global_plugins == $ xml_plugins)&&($ plugin_verso [$ key] == $ xml_plugin_version [$ key2] )){

echo'完全匹配';
break 2;

} else {

echo'模糊匹配';
}

}

}


I have a nested foreach loop going through 2 arrays with a conditional if - else. When if returns a value the else statement is also still running, why is that?

//$global_plugins is an array
//$xml_plugins is a string

foreach($global_plugins as $key => $global_plugins){
  foreach ((array) $xml_plugins as $key2 => $xml_plugins){

  if (($global_plugins == $xml_plugins) && ($plugin_verso[$key] == $xml_plugin_version[$key2])){ 

       echo 'Exact match'; 

  }else{

        echo 'Fuzzy match';

    }

  }

}

For this example the array has 10 values to match, when the if returns an "Exact match" it should not also return "Fuzzy match", yet this is what is happening.

For 1 matching value I get the echo output: "Exact match" one time and "Fuzzy match" x 10

解决方案

You should break the loops using the break statement.

foreach($global_plugins as $key => $global_plugins){
  foreach ((array) $xml_plugins as $key2 => $xml_plugins){

  if (($global_plugins == $xml_plugins) && ($plugin_verso[$key] == $xml_plugin_version[$key2])){ 

       echo 'Exact match'; 
       break 2;

  }else{

        echo 'Fuzzy match';
    }

  }

}

这篇关于嵌套的foreach如果不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆