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

时间:2012-04-19 07:31:22

标签: php arrays

假设我有第一个数组,$ aAllCities为

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

另一个数组,$ aNotSupportedCities为

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

是否可以获得这样的数组?

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

我想删除其他数组中存在的那些键的数组值

5 个答案:

答案 0 :(得分:2)

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

}

答案 1 :(得分:1)

试试这个:

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

希望这有帮助。

答案 2 :(得分:1)

其他答案是正确的,但更顺畅,更快捷的方法是:
$supportedCities = array_diff_key($aAllCities, $aNotSupportedCities);

这将返回$aAllCities中没有密钥的$aNotSupportedCities的所有值

注意,这会通过键来比较两个数组,因此您需要使$aNotSupportedCities看起来像这样:

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

祝你好运。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

$supportedCities = array_diff_key($aAllCities, array_values($aNotSupportedCities));