简体   繁体   中英

Removing Array Values From One Array By Comparing Keys Of Another Array

Suppose I have first array, $aAllCities as

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

And another array, $aNotSupportedCities as

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

Note, this compares the two arrays via their keys, so you will need to make your $aNotSupportedCities look like this:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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