在PHP中将令人困惑的逻辑与两个数组匹配?

在PHP中将令人困惑的逻辑与两个数组匹配?

问题描述:

I have this array which provides Geo-restriction information from API, this is an array list of countries where content is being BLOCKED :

Array ( [0] => GU [1] => PR [2] => CA [3] => VI [4] => US [5] => UM [6] => AS [7] => MP [8] => DE )

Now, I have another array which stores country-wise proxy information like this :

$proxies['US'] = 'my_us_proxy_url;
$proxies['DE'] = 'my_de_proxy_url;
$proxies['UK'] = 'my_uk_proxy_url;
$proxies['NL'] = 'my_nl_proxy_url;

I want to get value of the proxy which will allow user to bypass the country restriction i.e. a $proxies[KEY] value where KEY does not exist in the first array.

This is one of the snippet I tried but like everything else this is not the logic what is needed.

            $isBlocked = array_values;
            //print_r($isBlocked);
            if (in_array('US',$isBlocked))
            {
                echo 'US Blocked';
                foreach ($isBlocked as $value) {

                    if (!array_key_exists($value,$proxies)){
                        //Find first non blocked proxy and continue
                        echo "<br/>" . $value ;
                    }
                }

            }

我有这个数组提供来自API的地理限制信息,这是一个包含内容的国家的数组列表 阻塞: p>

数组([0] =&gt; GU [1] =&gt; PR [2] =&gt; CA [3] =&gt; VI [4 ] =&gt; US [5] =&gt; UM [6] =&gt; AS [7] =&gt; MP [8] =&gt; DE) p> blockquote>

现在,我有另一个数组存储国家代理信息,如下所示: p>

  $ proxies ['US'] ='my_us_proxy_url; 
 $ proxies ['  DE'] ='my_de_proxy_url; 
 $ proxies ['UK'] ='my_uk_proxy_url; 
 $ proxies ['NL'] ='my_nl_proxy_url; 
  code>  pre> 
 
 

我希望获得代理的价值,这将允许用户绕过国家/地区限制,即 $ proxies [KEY] code>值,其中 KEY code>在第一个数组中不存在。

这是我尝试过的一个片段,但是就像其他所有内容一样,这不是需要的逻辑。 p>

  $ isBlocked = array_values;  
  // print_r($ isBlocked); 
 if(in_array('US',$ isBlocked))
 {
 echo'US Blocked'; 
 foreach($ isBlocked as $ value){
 
 if(  !array_key_exists($ value,$ proxies)){
 //找到第一个非阻塞代理并继续
 echo“&lt; br /&gt;”  。  $ value; 
} 
} 
 
} 
   code>  pre> 
  div>

Use $key => $value structure in your foreach loop:

foreach ($proxies as $key => $value) {
    if (!in_array($key, $isBlocked)){
        //Find first non blocked proxy and continue
        echo "<br/>" . $value ;
    }
}

Demo!

Get the key from the proxies array via array_keys. Get the difference to the other array via array_diff. With large arrays that might a tad less expensive than foreach-loops.

That will be:

$data = ['GU', 'PR', 'CA', 'VI', 'US', 'UM', 'AS', 'MP', 'DE '];
$proxies['US'] = 'my_us_proxy_url';
$proxies['DE'] = 'my_de_proxy_url';
$proxies['UK'] = 'my_uk_proxy_url';
$proxies['NL'] = 'my_nl_proxy_url';

$result = array_diff_key($proxies, array_flip($data));