简体   繁体   English

通过比较另一个数组的键从一个数组中删除数组值

[英]Removing Array Values From One Array By Comparing Keys Of Another Array

Suppose I have first array, $aAllCities as 假设我有第一个数组$ aAllCities作为

Array
(
   [21] => London
   [9]  => Paris
   [17] => New York
   [3]  => Tokyo
   [25] => Shanghai
   [11] => Dubai
   [37] => Mumbai
)

And another array, $aNotSupportedCities as 另一个数组$ aNotSupportedCities为

Array
(
   [0] => 37
   [1] => 25
   [2] => 11
)

Is it possible to get an array like this ? 是否有可能得到这样的数组?

Array
(
   [21] => London
   [9]  => Paris
   [17] => New York
   [3]  => Tokyo
)

I want to remove array values of those keys that are present in other array 我想删除其他数组中存在的那些键的数组值

foreach($aAllCities as $key => $value) {
    if(in_array($key,$aNotSupportedCities)) {
        unset($aAllCities[$key]); 
    }

}

Try this: 尝试这个:

$aAllCities = array_flip( $aAllCities );
$aAllCities = array_diff( $aAllCities, $aNotSupportedCities );
$aAllCities = array_flip( $aAllCities );

Hope this helps. 希望这可以帮助。

The other answers are correct, but a smoother, faster way to do it is: 其他答案是正确的,但是更流畅,更快捷的方法是:
$supportedCities = array_diff_key($aAllCities, $aNotSupportedCities);

This will return all the values from $aAllCities that don't have keys in $aNotSupportedCities 这将从$aAllCities返回所有在$aAllCities中没有键的$aNotSupportedCities

Note, this compares the two arrays via their keys, so you will need to make your $aNotSupportedCities look like this: 注意,这通过它们的键比较两个数组,因此您需要使$aNotSupportedCities看起来像这样:

Array
(
   [37] => something
   [25] => doesn't really matter
   [11] => It's not reading this
)

Best of luck. 祝你好运。

$new = $aAllCities;
foreach($aNotSupportedCities as $id) {
  if (isset($new[$id]) {
    unset($new[$id]);
  }
}
$supportedCities = array_diff_key($aAllCities, array_values($aNotSupportedCities));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM