Array intersect on key in array?

前端 未结 4 1871
故里飘歌
故里飘歌 2020-12-11 01:02

I have an array that has countries:

array(
\'AF\'=>\'AFGHANISTAN\',
\'AL\'=>\'ALBANIA\',
\'DZ\'=>\'ALGERIA\',
\'AS\'=>\'AMERICAN SAMOA\',
);


        
相关标签:
4条回答
  • 2020-12-11 01:27
    $selection = array('AL', 'DZ');
    $filtered = array_intersect_key($countries, array_flip($selection));
    var_dump($filtered);
    
    0 讨论(0)
  • 2020-12-11 01:36

    Simply loop over the SECOND array, and fetch the values from the first. Vise versa seems unneeded inefficient indeed.

    So:

    $Arr1 = array(
    'AF'=>'AFGHANISTAN',
    'AL'=>'ALBANIA',
    'DZ'=>'ALGERIA',
    'AS'=>'AMERICAN SAMOA',
    );
    
    $Arr2 = array('AL', 'DZ');
    
    $result = array();
    foreach ($Arr2 as $cc){
      if (isset($Arr1[$cc])){
        $result[$cc] = $Arr1[$cc];
      }
    }
    print_r($result);
    

    I don't think that is inefficient.

    Edit addition: If you are 100% sure the $Arr2 contains only codes that can be found in $Arr1, you can of course skip the isset() test.

    0 讨论(0)
  • 2020-12-11 01:38

    I think this will help. Here is a function key_values_intersect that will work as you expected :)

    $longcodes = array(
        'AF' => 'AFGHANISTAN',
        'AL' => 'ALBANIA',
        'DZ' => 'ALGERIA',
        'AS' => 'AMERICAN SAMOA',
    );
    
    $code = array('AL', 'DZ');
    
    function key_values_intersect($haystack, $needle)
    {
        $tmp=array();
        foreach ($needle AS $key) {
            $tmp[$key] = $haystack[$key];
        }
        return $tmp;
    }
    
    
    print_r(key_values_intersect($longcodes,$code));
    
    0 讨论(0)
  • 2020-12-11 01:42

    If I understood correctly You have array of countries and array of needed countries and You want to create array with needed countries. If that, then You can try this:

    $countries = array ("AF"=>"AFGJANISTAN", "AL"=>"ALBANIA", "LV"=>"LATVIA", "USA"=>"UNITED STATES OF AMERICA");
    $needed  = array ("AF", "AL");
    
    $result = array ();
    foreach ($needed as $row) {
       if (in_array($row, $contries)) {
           $result[] = $countries[$row];
       }
    }
    var_dump($result);
    
    0 讨论(0)
提交回复
热议问题