PHP: How to compare keys in one array with values in another, and return matches?

前端 未结 4 1961
终归单人心
终归单人心 2020-12-30 06:10

I have the following two arrays:

$array_one = array(\'colorZero\'=>\'black\', \'colorOne\'=>\'red\', \'colorTwo\'=>\'green\', \'colorThree\'=>\'b         


        
相关标签:
4条回答
  • 2020-12-30 06:31

    If I am understanding this correctly:

    Returning a new array:

    $array_new = [];
    foreach($array_two as $key)
    {
        if(array_key_exists($key, $array_one))
        {
            $array_new[$key] = $array_one[$key];
        }
    }
    

    Stripping from $array_one:

    foreach($array_one as $key => $val)
    {
        if(array_search($key, $array_two) === false)
        {
            unset($array_one[$key]);
        }
    }
    
    0 讨论(0)
  • 2020-12-30 06:34

    Tell me if it works:

    for($i=0;$i<count($array_two);$i++){
      if($array_two[$i]==key($array_one)){
         $array_final[$array_two[$i]]=$array_one[$array_two[$i]];
         next($array_one);
      }
    }
    
    0 讨论(0)
  • 2020-12-30 06:38

    As of PHP 5.1 there is array_intersect_key (manual).

    Just flip the second array from key=>value to value=>key with array_flip() and then compare keys.

    So to compare OP's arrays, this would do:

    $result = array_intersect_key( $array_one , array_flip( $array_two ) );
    

    No need for any looping the arrays at all.

    0 讨论(0)
  • 2020-12-30 06:54

    <?php 
    $array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden');
    
    $array_two = array('colorOne', 'colorTwo', 'colorThree');
    
    print_r(array_intersect_key($array_one, array_flip($array_two))); 
    ?> 

    0 讨论(0)
提交回复
热议问题