0

假设我有第一个数组 $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
)

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

4

5 回答 5

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

}
于 2012-04-19T07:35:42.127 回答
1

试试这个:

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

希望这可以帮助。

于 2012-04-19T07:41:10.330 回答
1

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

这将返回所有$aAllCities没有键的值$aNotSupportedCities

请注意,这将通过它们的键比较两个数组,因此您需要使您的$aNotSupportedCities外观如下所示:

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

祝你好运。

于 2012-04-19T07:46:21.810 回答
0
$new = $aAllCities;
foreach($aNotSupportedCities as $id) {
  if (isset($new[$id]) {
    unset($new[$id]);
  }
}
于 2012-04-19T07:33:53.377 回答
0
$supportedCities = array_diff_key($aAllCities, array_values($aNotSupportedCities));
于 2012-04-19T07:40:14.920 回答